banner for writing 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'm not criticizing that - but I think there's a better way.

I create short scripts, like this one, for that 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.

writing to file illustration

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

This particular script isn't that useful. You wouldn't want a website to actually do this, 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... for that, you can use this.

Let's dive in!


const fs = require('fs')

let str="";

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

try {
  const data = fs.writeFileSync('test.txt', str)
  //file written successfully
} catch (err) {
  console.error(err)
}

First off, let me say: this looks more complicated than it would be in Python, or many other languages.

Sometimes, in the process of writing a snippet like this, I learn that it wasn't as simple as I thought. Then, it's educational.

This happened me with me, here, with the synchronous/asynchronous code distinction.

Whether your code runs in the order you wrote it in, or in a different order, is something you have to think about in JavaScript.

sync or async

The try/catch shown above is synchronous, which mean it's executed in the order it's written.

That's not always true in JS, since it's event loop is such that things can be run out of order.

That's not desirable here, however, which is why the synchronous code here is important: first it creates the block of text you want it to use, then it inserts it into a file.

In this case, first it goes through an array to generate random numbers 10 times, in a format that would work to write to a file.

Then, it writes that to file.

If there's an error, it notes it. Otherwise, it just runs to completion.

And that's it!