2017-06-15 78 views
0

正在使用一个小文件传输实用程序替换旧的基于电子邮件的系统以进行订单处理,并且我正在使用Nodejs,express以及其他一些库。fs模块writeFileStream实际上不是在磁盘上创建文件

目前的问题是我有数据拉过来很好,但我似乎无法实际将文件保存到磁盘的最后。

var file_url = `${config.poll.transUrl}/?location=${config.location}&transmission=${config.poll.transmission}`; 
console.log(file_url); 
var download_path = config.poll.folder; 
var filename = setFileName(); 
var fileStream = fs.createWriteStream(download_path + filename); 
fileStream.on('finish',()=>{ 
    console.log(`${filename} has been downloaded to: ${download_path}`); 
}); 
http.get(file_url, (res)=>{ 
    res.on('data', (data)=>{ 
    console.log(data.toString()); 
    fileStream.write(data); 
    }) 
    .on('end',()=>{ 
    fileStream.close(); 
    fileStream.end(); 
    }); 
}); 

这是我一直在使用的代码,它只是一个片段。假设所有变量都被设置并且是正确的类型,因为我已经确认了这种情况。

据我所知,fileStream.end()函数应该关闭流并将文件保存到磁盘,但它不这样做。我看着它应该在的文件夹中,什么都没有。

也为更多的信息,这里是我的配置对象:

module.exports = { location: 'CA', watch:{ folder: './watch/', transUrl: 'http://localhost:3289', transmission: 'send' }, poll:{ folder: './recieve', transUrl: 'http://localhost:3289', transmission: 'receive' } }

回答

1

做到这一点,正确的方法是用pipe

http.get(file_url, (res) => { 
    const filePath = path.join(download_path, filename) 
    const writeStream = fs.createWriteStream(filePath) 
    res.pipe(writeStream) 
    .on('error', (e) => console.error(e)) 
    .on('close',() => console.log(`file was saved to ${filePath}`)) 
}) 
0

最终找到了解决方法:

最终代码忽略增加了流作为数据的概念就会出现,数据纯粹是当前实现中的文本。

最终的代码如下:

var file_url = `${config.poll.transUrl}/?location=${config.location}&transmission=${config.poll.transmission}`; 
console.log(file_url); 
var download_path = config.poll.folder; 
var fileContent = ''; 
var filename = setFileName(); 
var fileStream = fs.createWriteStream(download_path + filename); 
fileStream.on('finish',()=>{ 
    console.log(`${filename} has been downloaded to: ${download_path}`); 
}); 
http.get(file_url, (res)=>{ 
    res.on('data', (data)=>{ 
    fileContent += data.toString(); 
    }) 
    .on('end',()=>{ 
    fs.writeFile(path.join(download_path, filename), fileContent,(err) =>{ 
     if(err){ 
     return console.error(err); 
     } 
     console.log('file was saved') 
    }) 
    }); 
});