Lub*_*bor 7 javascript asynchronous fs node.js
假设我们有这样一个程序:
// 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"}});
}
Run Code Online (Sandbox Code Playgroud)
我的问题是, will string1 to string1000 be gurantted to append to the same file in order?
由于fs.write是异步函数,我不确定每次调用fs.write()是如何执行的.我假设对每个字符串的函数调用应该放在某处another thread(比如callstack?),一旦完成上一次调用,就可以执行下一个调用.
我不确定我的理解是否准确.
编辑1
在评论和答案中,我看到fs.write多次写入同一文件而不等待是不安全的callback.但是如何写入流?
如果我使用以下代码,它会保证写作的顺序吗?
// 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();
Run Code Online (Sandbox Code Playgroud)
任何评论或更正都会有所帮助!谢谢!
该文件说,
请注意,
fs.write在不等待回调的情况下在同一文件上多次使用是不安全的.对于这种情况,强烈建议使用fs.createWriteStream.
使用流是有效的,因为流固有地保证写入它们的字符串的顺序与从它们读出的顺序相同.
var stream = fs.createWriteStream("./same/path/file.txt");
stream.on('error', console.error);
arr.forEach((str) => {
stream.write(str + '\n');
});
stream.end();
Run Code Online (Sandbox Code Playgroud)
仍然使用的另一种方法,fs.write但也确保按顺序发生的事情是使用promises来维护顺序逻辑.
function writeToFilePromise(str) {
return new Promise((resolve, reject) => {
fs.write("./same/path/file.txt", str, {flag: "a"}}, (err) => {
if (err) return reject(err);
resolve();
});
});
}
// for every string,
// write it to the file,
// then write the next one once that one is finished and so on
arr.reduce((chain, str) => {
return chain
.then(() => writeToFilePromise(str));
}, Promise.resolve());
Run Code Online (Sandbox Code Playgroud)