How to write an array to file with Node.js?

Sometimes, we want to write an array to file with Node.js.

In this article, we’ll look at how to write an array to file with Node.js.

How to write an array to file with Node.js?

To write an array to file with Node.js, we can create a write stream.

For instance, we write

const fs = require('fs');

const file = fs.createWriteStream('array.txt');

file.on('error', (err) => {
  /* error handling */
});

arr.forEach((v) => {
  file.write(v.join(', ') + 'n');
});

file.end();

to call fs.createWriteStream with the path of the file to write to.

Then we call arr.forEach to loop through the array and call file.write to write to the stringified version of the array to the the stream.

And once, we’re done, we call file.end to close the stream.

Conclusion

To write an array to file with Node.js, we can create a write stream.