Categories
JavaScript Answers

How to write to a CSV in Node.js?

Spread the love

Sometimes, we want to write to a CSV in Node.js.

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

How to write to a CSV in Node.js?

To write to a CSV in Node.js, we can use the fs.writeFile method,.

For instance, we write

const fs = require("fs");
const dataToWrite = "...";

fs.writeFile("./form-tracking/formList.csv", dataToWrite, "utf8", (err) => {
  if (err) {
    console.log("error");
  } else {
    console.log("saved!");
  }
});

to call fs.writeFile with the file path to write to.

dataToWrite has our CSV string that we want to write to the file path.

Then callback is called when the write operation is done or failed.

err in the callback has the error.

Conclusion

To write to a CSV 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 *