Write Files In NodeJS (Very Simple Examples)

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.

  1. To write files asynchronously:
    • require("fs").writeFile("MY.TXT", "TEXT");
    • require("fs").appendFile("MY.TXT", "TEXT");
  2. 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!

ⓘ 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.

 

 

TLDR – QUICK SLIDES

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

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

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short 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.

 

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.

 

 

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

1-write-async.js
// (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

2-write-sync.js
// (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)

3-write.js
// (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

4-stream-async.js
// (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() 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.

 

 

EXTRA 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 *