Huge problem with readFile dialog - insert image from file system


#1

Hey,

I have declared this in my main.js file:

ipcMain.on('openFile', (event, path) => {
      const {dialog} = require('electron')
      const fs = require('fs')
      dialog.showOpenDialog(function (fileNames) {
            // fileNames is an array that contains all the selected
          if(fileNames === undefined){
                  console.log("No file selected");
          }else{
                  readFile(fileNames[0]);
          }
      });

      function readFile(filepath){
         fs.readFile(filepath, 'utf-8', (err, data) => {
            if(err){
               alert("An error ocurred reading the file :" + err.message)
               return
            }
            // handle the file content
            event.sender.send('fileData', filepath)
      })
      }
})

I am using this function to load Images in my canvas object:

	$scope.loadImage = function () {

		const {
			ipcRenderer
		} = require('electron')
		ipcRenderer.send('openFile', () => {})
		ipcRenderer.on('fileData', (event, filepath) => {
			fabric.Image.fromURL(filepath, function (image) {

				image.set({
					scaleX: 0.5,
					scaleY: 0.5
				})


				canvas.add(image);
			})
		})

	};

Working, but really strage, when I choose an image from my file system:

1st time I insert an Image is OK – it is inserting one image
2nd time it inserts two instances of the choosen image
3rd time it inserts three instances of the choosen image
… and so on…

Really banging my head :slight_smile:


#2

Every time you call loadImage() it adds a listener for the fileData event to ipcRenderer. Easiest way to fix this is to use ipcRenderer.once instead of ipcRenderer.on.


#3

@enlight Thanks Vladim! Working like a charme :slight_smile: