假设我们有这样一个程序:
// imagine the string1 to string1000 are very long strings, which will take a while to be written to file system
var arr = ["string1",...,"string1000"];
for (let i = 1; i < 1000; i++) {
fs.write("./same/path/file.txt", arr[i], {flag: "a"}});
}
我的问题是,will string1 to string1000 be gurantted to append to the same file in order?
由于 fs.write 是异步函数,我不确定每次调用 fs.write() 是如何真正执行的。我假设对每个字符串的函数的调用应该放在another thread
(像一个callstack
?),一旦上一个调用完成,就可以执行下一个调用。
我不太确定我的理解是否准确。
Edit 1
正如评论和答案中一样,我看到fs.write
在不等待的情况下多次写入同一文件是不安全的callback
。但是 writestream 呢?
如果我使用下面的代码,是否能保证书写顺序?
// imagine the string1 to string1000 are very long strings, which will take a while to be written to file system
var arr = ["string1",...,"string1000"];
var fileStream = fs.createWriteFileStream("./same/path/file.txt", { "flags": "a+" });
for (let i = 1; i < 1000; i++) {
fileStream.write(arr[i]);
}
fileStream.on("error", () => {// do something});
fileStream.on("finish", () => {// do something});
fileStream.end();
任何评论或更正都会有帮助!谢谢!