writing to file illustration

How To Write To A File in JavaScript

Using A Short JS Script To Write to File

A few days ago, I saw someone on Twitter saying that, despite being a professional JavaScript developer for years, they still have to look up how to do basic functions.

I think there's a better way.

I create short scripts for this reason. Instead of googling something like 'how to write to a file in JS', I write very short code snippets that do this.

Then, when I need it, I just search my files for "write*file" and there it is.

This is how you write to a file, using JavaScript. As a bonus, it shows how to generate random numbers too.

You wouldn't want a website to do it this way, since there are better ways of storing data.

But if you want a script that does a calculation for you (say, random numbers) and writes it to a file, use this.

Using The Code

The JavaScript code to write to file is shown below.


const fs = require('fs')

let str="";

Array.from(Array(10)).forEach((x, i) => {	
    let rnd= Math.random() * (100);
    let rando=Math.ceil(rnd)+'\n';
    str=str+rando;
});

try {
  const data = fs.writeFileSync('test.txt', str)
} catch (err) {
  console.log("Sorry couldn't write to file.")
  console.error(err)
}

You can run it by saving the file as anything you want (example: "saver.js") and then executing it using node ("node saver.js").

Explaining the Code

I would say this looks more complicated than it would be in Python, or in many other languages. But it's still comprehensible.

First you create the thing you want to write to a file.

Then, in the try/catch block, you insert it into a file, or generate an error message if it fails. (It shouldn't fail.)

In this case, an array is filled with random generated numbers 10 times.

Then, that array is written to a file.

If there's an error, if the script can't print to file, the reason is printed to the console. Otherwise, the script just runs to completion.

Check test.txt in the directory where you run this file. It should have numerical values in it now.

Use It In Your Own Projects

And that's it: how to write to a file using JavaScript.

Save this to your own computer, and you won't have to look up how to write to a file anymore online either.

Feel free to adapt and reuse this under an MIT license.