3 Ways To Write Files In NodeJS (Sync, Async, Stream)

Welcome to a quick tutorial and examples on how to write files in NodeJS. Want to create, write, and append to files in NodeJS? It is sadly not that straightforward.

The common ways to write a file in NodeJS are:

  1. Write and append to files asynchronously.
    • require("fs").writeFile("FILE.TXT", "TEXT", (err)=>{});
    • require("fs").appendFile("FILE.TXT", "TEXT", (err)=>{});
  2. Write and append to files synchronously.
    • require("fs").writeFileSync("FILE.TXT", "TEXT");
    • require("fs").appendFileSync("FILE.TXT", "TEXT");
  3. Lastly, to write using a file stream.
    • const fs = require("fs");
    • const stream = fs.createWriteStream("FILE.TXT");
    • for (let i of ARRAY) { stream.write(i + "\r\n"); }
    • stream.end();

That should cover the basics, but read on for more examples!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Write Files Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

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.

 

1) WRITE & APPEND TO FILE (ASYNCHRONOUS)

1-write-append-async.js
// (A) FILE SYSTEM MODULE
const fs = require("fs");
 
// (B) WRITE TO FILE
fs.writeFile("demoA.txt", "Hello World", (err) => {
  if (err) { console.log(err); }
  console.log("Written");
});
 
// (C) APPEND TO FILE
fs.appendFile("demoA.txt", "Goodbye World", (err) => {
  if (err) { console.log(err); }
  console.log("Appended");
});

Yes, the basic file write and append is that simple – Just use the file system module writeFile() and appendFile(). Both of them take in 3 parameters – The filename, content to write, and callback function on complete.

 

 

2) WRITE & APPEND TO FILE (SYNCHRONOUS)

2-write-append-sync.js
// (A) FILE SYSTEM MODULE
const fs = require("fs");
 
// (B) WRITE FILE
try {
  fs.writeFileSync("demoB.txt", "Hello World");
} catch (err) {
  console.log(err);
}
console.log("Written");

// (C) APPEND FILE
try {
  fs.appendFileSync("demoB.txt", "Goodbye World");
} catch (err) {
  console.log(err);
}
console.log("Appended");

Look no further, writeFileSync() and appendFileSync() are just the synchronous variants of the previous example.

 

 

3) WRITE STREAM

3-write-stream.js
// (A) ARRAY TO WRITE
var data = ["Apple", "Banana", "Cherry", "Durian", "Elderberry"];

// (B) FILE SYSTEM + STREAM
const fs = require("fs"),
      stream = fs.createWriteStream("demoC.txt");

// (C) WRITE TO FILE
for (let i of data) { stream.write(i + "\r\n"); }
stream.end();
console.log("WRITTEN");

This is the so-called “roundabout” way of writing to a file. Just what is the difference here?

  • The previous writeFile() and appendFile() 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.

 

4) APPEND USING FILE STREAM

4-append-stream.js
const stream = fs.createWriteStream("demoC.txt", {"flags": "a"});

Lastly, to append to a file using file stream – Simply pass an “append” flag into the options {"flags": "a"}.

 

 

USEFUL BITS & LINKS

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

 

INFOGRAPHIC CHEAT SHEET

Write And Append To Files In NodeJS (Click To Enlarge)

 

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!

Leave a Comment

Your email address will not be published. Required fields are marked *