javascript Node.js WriteStream 同步
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24468830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js WriteStream synchronous
提问by rwallace
I'm writing a purely synchronous, single threaded command line program in node.js, which needs to write a single binary file, for which I'm using WriteStream
. My usage pattern is along the lines of:
我正在 node.js 中编写一个纯同步的单线程命令行程序,它需要编写一个二进制文件,我正在使用WriteStream
. 我的使用模式是:
var stream = fs.createWriteStream(file)
stream.write(buf1)
stream.write(buf2)
This seems to work, but the documentation says it's asynchronous and I want to make sure I'm not writing code that works 99% of the time. I don't care exactly when the data gets written as long as it's written in the specified order and no later than when the program exits, and the quantity of data is small so speed and memory consumption are not issues.
这似乎有效,但文档说它是异步的,我想确保我没有编写 99% 的时间都可以工作的代码。我不关心数据什么时候写入,只要按照指定的顺序写入并且不迟于程序退出时,并且数据量很小,因此速度和内存消耗不是问题。
I've seen mention of stream.end()
but it seems to work without it and I've also seen suggestions that calling it may actually be a bad idea if you're not using callbacks because it might end up getting called before all the data is written.
我已经看到提到,stream.end()
但它似乎没有它也能工作,我也看到一些建议,如果你不使用回调,调用它实际上可能是一个坏主意,因为它可能最终在所有数据写入之前被调用。
Is my approach correct (given that I want purely synchronous) or is there anything I need to watch out for?
我的方法是否正确(假设我想要纯同步)或者我需要注意什么?
采纳答案by vkurchatkin
You can do this, the only problem can be if you create two or more concurrent streams for the same path: the order of writes from different streams will be undefined. By the way, there is a synchronous fs write stream implementation in node: fs.SyncWriteStream
. It's kind of private and requires fd
as an argument, but if you really want it...
您可以这样做,唯一的问题是如果您为同一路径创建两个或多个并发流:来自不同流的写入顺序将是未定义的。顺便说一下,node: 中有一个同步的 fs 写流实现fs.SyncWriteStream
。它有点私密,需要fd
作为参数,但如果你真的想要它......
回答by Jay Edwards
I'm working on a timing-critical API, where a new file has to have been written and its stream completely handled before the next action can be performed. The solution, in my case (and, quite possibly, that of the OP's question) was to use:
我正在开发一个对时间要求严格的 API,在该 API 中,必须写入新文件并在执行下一个操作之前完全处理其流。在我的情况下(并且很可能是 OP 的问题),解决方案是使用:
writer.on('finish', () => {
console.error('All writes are now complete.');
});
as per the fs Event: 'finish'
documentation