简体   繁体   English

将文件保存在指定目录 Node.js

[英]Saving file in specified directory Node.js

I want to save an image using fs.writeFile, but I'm not able to do this.我想使用 fs.writeFile 保存图像,但我无法做到这一点。

The path in which i want to do this: C:\\Users\\poz\\lotos\\images\\1232133123@gmail.com我要执行此操作的路径: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' } [错误:ENOENT:没有那个文件或目录,打开'C:\\Users\\poz\\lotos\\images\\1232133123@gmail.com\\1602604489722.jpeg'] { errno: -4058, code: 'ENOENT', syscall: '打开',路径:'C:\\Users\\poz\\lotos\\images\\1232133123@gmail.com\\1602604489722.jpeg' }

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.以避免与操作系统相关的问题或缺少尾部斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM