Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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