繁体   English   中英

Node.js WriteStream 同步

[英]Node.js WriteStream synchronous

我正在 node.js 中编写一个纯同步的单线程命令行程序,它需要编写一个二进制文件,为此我正在使用WriteStream 我的使用模式大致如下:

var stream = fs.createWriteStream(file)
stream.write(buf1)
stream.write(buf2)

这似乎可行,但文档说它是异步的,我想确保我没有编写 99% 的时间都有效的代码。 我不关心数据的确切写入时间,只要它是按照指定的顺序写入的,并且不迟于程序退出的时间,而且数据量很小,所以速度和 memory 消耗都不是问题。

我已经看到提到stream.end()但它似乎没有它也可以工作,而且我还看到了一些建议,如果你不使用回调,调用它实际上可能是一个坏主意,因为它可能最终会被调用数据被写入。

我的方法是否正确(假设我想要纯同步)还是我需要注意什么?

您可以这样做,唯一的问题是,如果为同一路径创建两个或更多并发流:来自不同流的写入顺序将是未定义的。 顺便说一句,节点中有一个同步fs写入流实现: fs.SyncWriteStream 这是私人的,需要fd作为参数,但如果你真的想要它...

 const writeToLocalDisk = (stream, path) => { return new Promise((resolve, reject) => { const istream = stream; const ostream = fs.createWriteStream(path); istream.pipe(ostream); istream.on("end", () => { console.log(`Fetched ${path} from elsewhere`); resolve(); }); istream.on("error", (err) => { console.log(JSON.stringify(err, null, 2)); resolve(); }); }); }; // Then use an async function to perform sequential-like operation async function sequential (stream) { const path = ""; await writeToLocalDisk(stream, path); console.log('other operation here'); }

我正在研究一个时序关键型API,在这个API中必须编写一个新文件并在完成下一个操作之前完全处理它的流。 在我的情况下(并且很可能是OP的问题)的解决方案是使用:

writer.on('finish', () => {
 console.error('All writes are now complete.');
});

根据fs Event: 'finish'文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM