Welcome to a quick tutorial and examples on how to write files in NodeJS. Want to create, write, and append to files in NodeJS? Things are a little bit confusing for beginners in NodeJS.
There are 2 general ways to write files in NodeJS – Asynchronous and synchronous.
- To write files asynchronously:
require("fs").writeFile("MY.TXT", "TEXT");
require("fs").appendFile("MY.TXT", "TEXT");
- To write files synchronously:
require("fs").writeFileSync6("MY.TXT", "TEXT");
require("fs").appendFileSync("MY.TXT", "TEXT");
That covers the basics, but read on for the details!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
WRITE & APPEND TO FILES IN NODEJS
All right, let us now get into the examples of how to write and append to files in NodeJS.
ASYNCHRONOUS VS SYNCHRONOUS WRITE!?
Long story short:
- Asynchronous write – NodeJS will not wait for the file write to complete. The rest of the script will continue to run, while the file write still goes on in the background.
- Synchronous write – NodeJS will wait for the file write to complete. The rest of the script cannot continue until the writing process is complete.
EXAMPLE 1) ASYNCHRONOUS FILE WRITE
// (A) FILE SYSTEM MODULE
const fs = require("fs");
// (B) WRITE TO FILE
fs.writeFile("demoA.txt", "Hello", err => {
if (err) { console.log(err); }
console.log("Written");
});
// (C) APPEND TO FILE
fs.appendFile("demoA.txt", "Goodbye", err => {
if (err) { console.log(err); }
console.log("Appended");
});
This should be straightforward enough, writeFile(FILE, DATA, CALLBACK)
and appendFile(FILE, DATA, CALLBACK)
. Once again, for those who are new – These are asynchronous. The rest of the script will continue to run, it does not wait for the file writer to complete.
P.S. Use the callback function to run “the next step” when the write is complete.
EXAMPLE 2) SYNCHRONOUS FILE WRITE
// (A) FILE SYSTEM MODULE
const fs = require("fs");
// (B) WRITE FILE
try { fs.writeFileSync("demoB.txt", "Hello"); }
catch (err) { console.log(err); }
console.log("Written");
// (C) APPEND FILE
try { fs.appendFileSync("demoB.txt", "Goodbye"); }
catch (err) { console.log(err); }
console.log("Appended");
Look no further, writeFileSync()
and appendFileSync()
are just the synchronous variants of the previous example. Beginners may be more comfortable using these, but take note – It blocks the rest of the script from running. This is bad if you are writing huge chunks of data.
EXAMPLE 3) FILE WRITE (LOW LEVEL)
// (A) FILE SYSTEM MODULE
const fs = require("fs");
// (B) OPEN & WRITE FILE
fs.open("demoC.txt", "a", (err, handle) => {
// (B1) ON ERROR
if (err) { console.log(err); }
// (B2) WRITE TO FILE
else {
fs.write(handle, "HELLO", (err, bytes) => {
if (err) { console.log(err.message); }
else { console.log(`Written - ${bytes} bytes`); }
});
}
});
If you prefer to have “more control”, use the “raw” fs.write()
. Take note of how this works, we have to manually open and create a file first; fs.write()
will not create the file, and strictly does “write to file” only.
EXAMPLE 4) WRITE STREAM
// (A) ARRAY TO WRITE
var data = ["Apple", "Banana", "Cherry"];
// (B) FILE SYSTEM + STREAM
const fs = require("fs"),
stream = fs.createWriteStream("demoC.txt");
// stream = fs.createWriteStream("demoC.txt", {"flags": "a"});
// (C) WRITE TO FILE
stream.on("finish", () => console.log("WRITTEN"));
data.forEach((v,i) => {
stream.write(v + "\r\n");
if (i==2) { stream.end(); } // close the stream!
});
Lastly, we have a so-called “roundabout” way of writing to a file. Just what is the difference here?
- The previous
writeFile()
andappendFile()
will write all at once. That is not good when dealing with massive amounts of data. - File stream, on the other hand, allows us to write line-by-line or block-by-block. This is much more efficient and will not use as much memory.
EXTRAS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
- File System – NodeJS
- Node.js Streams: Everything you need to know – FreeCodeCamp
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!