繁体   English   中英

NodeJS FS(writeFile)错误

[英]Error with NodeJS FS (writeFile)

这是我的路由器中负责管理我的上传的部分:

fs.readFile(files.photo.path, function (err, data) {
    // Here is the futur name of my file (ex: SERVER_PATH/images/moka/moka22/11/2016_1.jpg)
    var newPath = __dirname + "/images/moka/moka" + new Date().toLocaleDateString() + "_" + Math.floor(Math.random() * 10) + 1 + "." + ext;
    fs.writeFile(newPath, data, function (err) {
      if(err) {
        res.render('error', { error: err, message: "Erreur lors de l'upload"});
      } else {
        // insctructions
        });
      }
    });
  });

当代码被触发时,我有这个错误:

Error: ENOENT: no such file or directory, open 'D:\projects\raspberry\routes\images\moka\moka2016-11-22_91.jpg'
at Error (native)

如果我很了解fs doc( https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback ):

fs.writeFile(theNameOfTheFuturFile, theDataToPutIn, callback);

所以我有点困惑。

对不起,我的英语,可能不好,我希望你猜我的意思是:)

谢谢。

问题可能是您正在写入的目录不存在。

因此请确保它存在:

fs.readFile(files.photo.path, function (err, data) {
    var dirPath = __dirname + "/images/moka/moka";
    if (!fs.existsSync(dirPath)){
        fs.mkdirSync(dirPath);
    }
    ...

或手工完成。

暂无
暂无

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

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