create a csv file in javascript

To create a CSV file using JavaScript, we can make use of the fs (filesystem) module in Node.js. The fs module provides methods that enable us to work with the file system.

Here's a code snippet that creates a CSV file named data.csv with the content provided in the csvContent variable:

index.tsx
const fs = require('fs');

const csvContent = "Name, Age, Gender\nJohn, 25, Male\nJane, 27, Female";

fs.writeFile("data.csv", csvContent, (err) => {
    if (err) throw err;
    console.log('CSV file created successfully!');
});
229 chars
9 lines

In the above code, we require the fs module and then create a CSV content in a variable named csvContent. We then use the writeFile method to write the CSV content to a data.csv file. Finally, we use a callback function to log a message to the console if the file creation was successful.

This is one way to create a CSV file using JavaScript. However, there are other modules and libraries available that can simplify and enhance the process.

gistlibby LogSnag