我对这些片段之间的最佳解决方案犹豫不决:
simple_client({
method: 'get',
path: key,
id: 'download'
})
.then(req => new Promise((resolve, reject) => {
const write_stream = fs.createWriteStream(path);
req.on('result', (err, res) => {
if (err) {
reject(err);
}
res.pipe(write_stream);
res.on('end', () => {
console.log('Done!');
resolve();
});
});
req.end();
}))
.then(() => {
console.log(`Is it safe to touch ${path} file here?`);
});
或
simple_client({
method: 'get',
path: key,
id: 'download'
})
.then(req => new Promise((resolve, reject) => {
const write_stream = fs.createWriteStream(path);
req.on('result', (err, res) => {
if (err) {
reject(err);
}
res.pipe(write_stream);
write_stream.on('finish', () => {
console.log('Done!');
resolve();
});
});
req.end();
}))
.then(() => {
console.log(`Is it safe to touch ${path} file here?`);
});
默认情况下,当源Readable流发出“ end”消息时,在目标可写流上调用stream.end()
因此,当从可读流中发出“结束”事件时,我是否可以假定文件已完全写入并关闭了?因此,第一个代码片段就足够了。感谢您的帮助!