How to write files in Node.js?

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.