Suppose we have a program like this:
// 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"}}); }
My question is: will string1 to string1000 be gurantted to append to the same file in order?
Since fs.write is an asynchronous function, I'm not sure how each fs.write () call is made. I assume that the function call for each line should be placed somewhere in another thread
(e.g. callstack
?), And as soon as the previous call is made, the next call can be made.
I am not sure, as far as I understand.
Change 1
As in the comments and answers, I see that fs.write
not safe to write to the same file multiple fs.write
without waiting for a callback
. But what about writestream?
If I use the following code, would I guarantee the spelling order?
// 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();
Any comments or corrections will be helpful! Thanks!