Using Spreadsheets in Node.js Without External Libraries

When working with spreadsheets in Node.js, it's common to reach for libraries like node-xlsx or exceljs for ease of use.

But, if you are building simple or prefer not to use external libraries, you can still read from and write to spreadsheets by treating them as CSV files.

A CSV is just Comma-Separated Values in a plain-text format for representing spreadsheet data.

Each line in the file corresponds to a row in the spreadsheet, and each value within that line is separated by a comma, representing different cells. While this lacks the features of full Excel files (like styling or multiple sheets), it's widely supported and sufficient for a lot of manipulation tasks.

Reading from a CSV File

Using the built-in module called fs allows you to work with the file system on your computer, including reading from and writing to files.

Here's how you can use it to read data from a CSV file:

const fs = require('fs');

// Asynchronously read data from a CSV file
// Use fs.readFileSync() for a synchronous version
fs.readFile('data.csv', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the file:', err);
    return;
  }

  // Split the file into lines
  const lines = data.split('\n');

  // Iterate over each line to access individual rows
  lines.forEach((line) => {
    // Split each line by comma to access individual values
    const values = line.split(',');
    console.log(values);
  });
});

Writing to a CSV File

You can easily convert your data into a CSV format and write it to a file:

const fs = require('fs');

// Sample data to write to the file
const rows = [
  ['Name', 'Age', 'City'],
  ['Alice', '24', 'New York'],
  ['Bob', '30', 'San Francisco']
];

// Convert the data to a CSV format
const csvContent = rows.map(row => row.join(',')).join('\n');

// Asynchronously write data to a CSV file
// Use fs.writeFileSync() for a synchronous version
fs.writeFile('output.csv', csvContent, 'utf8', (err) => {
  if (err) {
    console.error('Error writing the file:', err);
    return;
  }

  console.log('File has been written successfully');
});

Notes

This approach has some limitations and for more advanced spreadsheet operations, you may still want to consider using specialized libraries to get it done quickly.

Nodejs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.