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\[email protected]

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\[email protected]\1602604489722.jpeg'] { errno: -4058, code: 'ENOENT', syscall: 'open', path: 'C:\Users\poz\lotos\images\[email protected]\1602604489722.jpeg' }

4
  • try mkdirp.sync(dir) Commented Oct 13, 2020 at 16:09
  • @ManuelSpigolon thanks man it's working. I thought it was fs.writeFile problem :P Commented Oct 13, 2020 at 16:14
  • 1
    FYI, it makes no sense to construct an absolute path in the dir variable, create that directory and then not use that same variable when constructing the file name. Commented Oct 13, 2020 at 16:21
  • On the beginning I tried to make everything by dir, but it didn't worked so I tried to fix it by myself by changing the path. Commented Oct 13, 2020 at 16:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.