是否可以安全地假设在完成“ fs.writeFileStream”写入和关闭管道后关闭文件后触发读取流“ end”事件?

时间:2018-08-31 00:29:24

标签: node.js stream

我对这些片段之间的最佳解决方案犹豫不决:

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 pipe documentation说:

  

默认情况下,当源Readable流发出“ end”消息时,在目标可写流上调用stream.end()

因此,当从可读流中发出“结束”事件时,我是否可以假定文件已完全写入并关闭了?因此,第一个代码片段就足够了。感谢您的帮助!

0 个答案:

没有答案