Categories
JavaScript Answers

How to write files in Node.js?

Spread the love

Sometimes, we want to write files in Node.js.

In this article, we’ll look at how to write files in Node.js.

How to write files in Node.js?

To write files in Node.js, we can use the fs.writeFile method.

For instance, we write

const fs = require('fs');

fs.writeFile("/tmp/test", "Hey there!", (err) => {
  if (err) {
    return console.log(err);
  }
  console.log("The file was saved!");
});

to call fs.writeFile with the path to write the file to, the file content string, and a callback that’s run when writeFile is finished running.

If there’s an error, then err will be set.

Conclusion

To write files in Node.js, we can use the fs.writeFile method.

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 *