Writing CSV Files

Introduction

CSV (Comma-Separated Values) files are one of the most popular formats for storing tabular data. They are widely used to export reports, save employee records, store customer information, generate invoices, and exchange data between different applications.

Node.js allows developers to create and write CSV files easily using external packages. Writing CSV files is especially useful when applications need to generate reports or export structured data that can later be opened in Microsoft Excel, Google Sheets, or other spreadsheet software.

For automation engineers, writing CSV files is commonly used to export test results, generate execution reports, save API responses, record performance metrics, and create reusable test data.


What is Writing a CSV File?

Writing a CSV file means creating a new CSV file or saving structured data into an existing CSV file.

Each row in the CSV file represents one record, while commas separate individual values.

Example:

id,name,department
1,John,HR
2,Alice,IT
3,Bob,Finance

Why Write CSV Files?

Writing CSV files allows applications to:

  • Export reports

  • Save employee records

  • Store customer information

  • Generate invoices

  • Export database records

  • Save automation test results

  • Create data files for future use


Installing the CSV Writer

Node.js does not include built-in support for writing CSV files.

Install the csv-writer package.

npm install csv-writer

Import Required Module

const createCsvWriter = require("csv-writer").createObjectCsvWriter;

Creating a CSV Writer

const csvWriter = createCsvWriter({
    path: "employees.csv",
    header: [
        { id: "id", title: "ID" },
        { id: "name", title: "NAME" },
        { id: "department", title: "DEPARTMENT" }
    ]
});

Explanation

PropertyDescription
pathCSV file name
headerColumn names of the CSV file
idObject property name
titleHeader displayed in the CSV file

Example 1: Write Employee Data

const createCsvWriter = require("csv-writer").createObjectCsvWriter;

const csvWriter = createCsvWriter({
    path: "employees.csv",
    header: [
        { id: "id", title: "ID" },
        { id: "name", title: "NAME" },
        { id: "department", title: "DEPARTMENT" }
    ]
});

const employees = [
    {
        id: 1,
        name: "John",
        department: "HR"
    },
    {
        id: 2,
        name: "Alice",
        department: "IT"
    },
    {
        id: 3,
        name: "Bob",
        department: "Finance"
    }
];

csvWriter.writeRecords(employees)
    .then(() => {
        console.log("CSV file created successfully.");
    });

Sample Output

CSV file created successfully.

Generated employees.csv

ID,NAME,DEPARTMENT
1,John,HR
2,Alice,IT
3,Bob,Finance

Example 2: Write Student Records

const createCsvWriter = require("csv-writer").createObjectCsvWriter;

const csvWriter = createCsvWriter({
    path: "students.csv",
    header: [
        { id: "rollNo", title: "ROLL_NO" },
        { id: "name", title: "NAME" }
    ]
});

csvWriter.writeRecords([
    {
        rollNo: 101,
        name: "Alice"
    },
    {
        rollNo: 102,
        name: "David"
    }
]).then(() => {
    console.log("Students exported.");
});

Sample Output

Students exported.

Example 3: Export Product Details

const createCsvWriter = require("csv-writer").createObjectCsvWriter;

const csvWriter = createCsvWriter({
    path: "products.csv",
    header: [
        { id: "product", title: "PRODUCT" },
        { id: "price", title: "PRICE" }
    ]
});

csvWriter.writeRecords([
    {
        product: "Laptop",
        price: 75000
    },
    {
        product: "Mouse",
        price: 800
    }
]).then(() => {
    console.log("Products exported.");
});

Sample Output

Products exported.

Real-World Example

Generate an employee report.

const createCsvWriter = require("csv-writer").createObjectCsvWriter;

const csvWriter = createCsvWriter({
    path: "employee-report.csv",
    header: [
        { id: "id", title: "ID" },
        { id: "employee", title: "EMPLOYEE" },
        { id: "salary", title: "SALARY" }
    ]
});

const report = [
    {
        id: 1,
        employee: "John",
        salary: 60000
    },
    {
        id: 2,
        employee: "Alice",
        salary: 70000
    }
];

csvWriter.writeRecords(report)
    .then(() => {
        console.log("Report generated.");
    });

Sample Output

Report generated.

Automation Testing Example

Writing CSV files is widely used in automation frameworks.

Playwright Example

Export test execution results.

const createCsvWriter = require("csv-writer").createObjectCsvWriter;

const csvWriter = createCsvWriter({
    path: "playwright-results.csv",
    header: [
        { id: "test", title: "TEST" },
        { id: "status", title: "STATUS" }
    ]
});

csvWriter.writeRecords([
    {
        test: "Login Test",
        status: "Passed"
    }
]);

Selenium Example

Generate a Selenium execution report.

const createCsvWriter = require("csv-writer").createObjectCsvWriter;

const csvWriter = createCsvWriter({
    path: "selenium-report.csv",
    header: [
        { id: "scenario", title: "SCENARIO" },
        { id: "result", title: "RESULT" }
    ]
});

csvWriter.writeRecords([
    {
        scenario: "Search Product",
        result: "Passed"
    }
]);

Cypress Example

Export API validation results.

const createCsvWriter = require("csv-writer").createObjectCsvWriter;

const csvWriter = createCsvWriter({
    path: "cypress-report.csv",
    header: [
        { id: "api", title: "API" },
        { id: "status", title: "STATUS" }
    ]
});

csvWriter.writeRecords([
    {
        api: "GET Users",
        status: "Success"
    }
]);

API Testing Example

Save API request history.

const createCsvWriter = require("csv-writer").createObjectCsvWriter;

const csvWriter = createCsvWriter({
    path: "api-history.csv",
    header: [
        { id: "endpoint", title: "ENDPOINT" },
        { id: "method", title: "METHOD" }
    ]
});

csvWriter.writeRecords([
    {
        endpoint: "/users",
        method: "POST"
    }
]);

Data-Driven Testing Example

Export processed employee data.

const createCsvWriter = require("csv-writer").createObjectCsvWriter;

const csvWriter = createCsvWriter({
    path: "employees-export.csv",
    header: [
        { id: "name", title: "NAME" },
        { id: "department", title: "DEPARTMENT" }
    ]
});

csvWriter.writeRecords([
    {
        name: "John",
        department: "HR"
    }
]);

Common Mistakes

Forgetting to Install the Package

Incorrect:

const createCsvWriter = require("csv-writer").createObjectCsvWriter;

without installing:

npm install csv-writer

Using Incorrect Header IDs

Incorrect:

header: [
    {
        id: "employeeName",
        title: "NAME"
    }
]

If your data object contains:

{
    name: "John"
}

The id should be:

header: [
    {
        id: "name",
        title: "NAME"
    }
]

Forgetting to Call writeRecords()

Creating the writer alone does not generate the CSV file.

Always call:

csvWriter.writeRecords(data);

Best Practices

  • Store CSV files in a dedicated reports or exports folder.

  • Use meaningful column names.

  • Keep object property names consistent with header IDs.

  • Export only required data.

  • Handle promise rejections when writing files.

  • Use CSV files for reports and data exchange.

  • Verify the generated CSV file after writing.


Conclusion

Writing CSV files is an essential skill for Node.js developers. By using the csv-writer package, you can quickly generate structured CSV files that are compatible with Excel, Google Sheets, and many other applications.

For automation engineers, CSV files are invaluable for exporting reports, recording execution results, storing API responses, and generating reusable test data.

Mastering CSV file writing is an important step toward building professional Node.js applications and automation frameworks.


Frequently Asked Questions (FAQs)

What package is commonly used to write CSV files in Node.js?

The csv-writer package.


How do I install the CSV writer?

npm install csv-writer

What does writeRecords() do?

It writes JavaScript objects into a CSV file.


Can csv-writer create a new CSV file?

Yes. If the file does not exist, it is created automatically.


What is the purpose of the header property?

It defines the CSV column names and maps them to object properties.


Why are CSV files important in automation testing?

Automation engineers use CSV files to export reports, save test results, store API responses, maintain execution history, and support data-driven testing.


Key Takeaways

  • CSV files store tabular data in rows and columns.

  • Node.js commonly uses the csv-writer package to write CSV files.

  • Install the package using npm install csv-writer.

  • Use createObjectCsvWriter() to create a CSV writer.

  • Use writeRecords() to write JavaScript objects into a CSV file.

  • Define column headers using the header property.

  • Store reports and exported data in dedicated folders.

  • CSV files are widely used in Playwright, Selenium, Cypress, API testing, and Node.js applications.

  • CSV files simplify report generation and data exchange.

  • Mastering CSV file writing is essential for backend development and automation testing.