Nodejs流写,读,写

时间:2014-10-02 20:34:53

标签: node.js express request

基本上我要做的是从外部源写入我的文件,从该文件读取,然后用一些更新的样式重新写入它。我正在做这个图像。例如:

var rawImg = urlHtml('img').attr('src'); // got the image from a website! 

var wStream = request(rawImg).pipe(fs.createWriteStream(__dirname + '/public/img/test.jpg')); //write img to file

var rStream = fs.createReadStream(__dirname + '/public/img/test.jpg', {encoding: 'base64'}); // read img from file
var wStream2 = fs.createWriteStream(__dirname + '/public/img/test-result.jpg') // output

图像确实保存到文件中,但是当我尝试读取它时,我总是得到错误:{[错误:产生ENOENT]代码:'ENOENT',错误:'ENOENT',系统调用:'spawn'} - 哪个意味着它甚至还没有

1 个答案:

答案 0 :(得分:0)

您在创建文件之前尝试读取该文件。尝试先等待文件关闭:

var wStream = request(rawImg).pipe(fs.createWriteStream(__dirname + '/public/img/test.jpg'));

wStream.on('close', function() {
  var rStream = fs.createReadStream(__dirname + '/public/img/test.jpg', {encoding: 'base64'});
  var wStream2 = fs.createWriteStream(__dirname + '/public/img/test-result.jpg');
});