fs.createWriteStream,没有这个文件或目录,在Node.js中打开。

6
我希望将从另一台服务器获取的文件保存在我的服务器上,但问题是当我调用createWriteStream时,它给出了以下错误:
no such file or directory, open E:\pathtoproject\myproject\public\profile_14454.jpg
以下是我的代码,位于E:\ pathtoproject \ myproject \ modules \ dowload.js中:
request.head(infos.profile_pic, function(err, res, body) {
  const completeFileName = '../public/profile_14454.' + res.headers['content-type'].split('/')[1];
  var imageStream = fs.createWriteStream(completeFileName);
  imageStream.on('open', function(fd) {
    console.log("File open");
    request(infos.profile_pic).pipe(imageStream).on('close', function(body) {
      consoleLog('Profile pic saved');
      console.log('This is the content of body');
      console.log(body);
      connection.query('UPDATE user set photo=? where id=?', [completeFileName, lastID], function(err, result, fields) {
        if (err) {
          consoleLog('Error while update the profile pic');
        }
      });
    })
  });
});

当我移除目录../public/并只留下文件名profile_14454.' + res.headers['content-type'].split('/')[1]时,它可以工作,但该文件将被保存在项目根目录(E:\pathtoproject\myproject\)中。那么我做错了什么?如何将文件保存在public目录下?我正在使用nodeJS 8.9.4。

为什么不尝试使用完整路径而不是使用点呢? - Syed Ayesha Bebe
如果你在代码中使用 console.log(__dirname) ,你可以得到当前脚本的工作目录。试着以相对于 __dirname 的路径创建你的图像路径。 - Alex Michailidis
1个回答

0

我用我的小代码尝试了一下。

var fs = require("fs");
var data = 'Simply Easy Learning';

// Create a writable stream
var writerStream = fs.createWriteStream('./airo/output.txt');

// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');

// Mark the end of file
writerStream.end();

// Handle stream events --> finish, and error
writerStream.on('finish', function() {
    console.log("Write completed.");
});

writerStream.on('error', function(err){
   console.log(err.stack);
});

console.log("Program Ended");

我的代码在这个路径下 E:\syed ayesha\nodejs\nodejs,现在我想把文件存储在这个路径下的airo文件夹中。所以我使用了一个点来进行存储。希望这可以帮到你。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接