1

I want to save an image using fs.writeFile, but I'm not able to do this.

The path in which i want to do this: C:\Users\poz\lotos\images\1232133123@gmail.com

My code:

    var d = new Date();
    var n = d.getTime() + ".jpeg";
    var dir = "C:/Users/poz/lotos/images/" + email;

    mkdirp(dir);

    var data = image.replace(/^data:image\/jpeg;base64,/,'');

    var dir2 = dir + "/";

    fs.writeFile(__dirname +'/../../images/' + email + '/' + n, data, 'base64' , function(err){
      if (err)
        return console.log(err);
    });

*The folder is created.

An error which I'm getting:

[Error: ENOENT: no such file or directory, open 'C:\Users\poz\lotos\images\1232133123@gmail.com\1602604489722.jpeg'] { errno: -4058, code: 'ENOENT', syscall: 'open', path: 'C:\Users\poz\lotos\images\1232133123@gmail.com\1602604489722.jpeg' }

Casper222
  • 101
  • 2
  • 9

1 Answers1

2
mkdirp(dir)

Returns a promise that is not awaited.

You should call

mkdirp.sync(dir)

Or rewrite your code in an async style.

I would suggest using:

const savePath = require('path').join(__dirname, '/../../images/', email)

to avoid issue related to OS or missing trailing slash.

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73