Categories
Node.js Tips

Node.js Tips — CORS, Excel Files, and CSVs

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Reading Excel File Using Node.js

There are a few packages to let us read Excel files in a Node app.

One package we can use is the node-xlsx package.

To use it, we write:

const xlsx = require('node-xlsx');
const path = require('path');
const obj = xlsx.parse(path.join(__dirname, '/myFile.xlsx'));

We can pass in a path to parse the Excel file from the path.

Also, we can write:

const xlsx = require('node-xlsx');
const path = require('path');
const obj = xlsx.parse(fs.readFileSync(path.join(__dirname, '/myFile.xlsx'));

to parse a buffer, which readFileSync returns.

ExcelJS is another package that we can use to parse workbooks.

For instance, we can write:

const ExcelJS = require('exceljs');
const path = require('path');
const workbook = new Excel.Workbook();
const filename = path.join(__dirname, '/myFile.xlsx');
workbook.xlsx.readFile(filename);
  .then(() => {
    // use workbook
  });

to read from a workbook.

Also, we can write:

const workbook = new Excel.Workbook();
stream.pipe(workbook.xlsx.createInputStream());

to read from a stream.

Pass Variables to JavaScript in Express

We can pass variables to Express templates by passing in a 2nd argument to res.render .

For instance, we can write:

app.get('/foo.js', (req, res) => {
  res.set('Content-Type', 'application/javascript');
  res.render('foo', { foo: { bar: 'baz' } });
});

Then in the foo template, we can write:

<script>
  const foo = <%- JSON.stringify(foo) %>;
</script>

We’re using an EJS template, so we interpolate variables with <%- %> .

Also, we’ve to call JSON.stringify to convert it to a string so we can interpolate it.

Write to a CSV in Node.js

We can use csv-stringify package to create a CSV string from a nested array.

Then we can use fs.writeFile to write the CSV string to a file.

For instance, we can write:

import stringify from 'csv-stringify';
import fs from 'fs';

let data = [];
let columns = {
  id: 'id',
  name: 'name'
};

for (let i = 0; i < 100; i++) {
  data.push([i, `name ${i}`]);
}

stringify(data, { header: true, columns }, (err, output) => {
  if (err) throw err;
  fs.writeFile('file.csv', output, (err) => {
    if (err) throw err;
    console.log('csv saved.');
  });
});

We create a nested array with a columns array for the columns.

The key in columns are the field name. The value in columns are the heading names.

Then we populate our data into the data array.

Next, we call stringify to turn the heading and data into one CSV string.

The first argument is the data.

Then 2nd is an object with some options.

header set to true means we show some header.

columns is for setting the column fields.

The columns are populated by the position of each item in each row.

For each row in data , the first entry is the id and the 2nd is the name .

The callback is called when the CSV conversion is done.

output has the CSV string.

Then we can fs.writeFile to write the string to a file.

Reload Express.js Routes Changes without Manually Restarting Server

We can make an Express app restart automatically when we change the code by using Nodemon.

We can run our app with nodemon instead of node once it’s installed.

To install it, we run:

npm install -g nodemon

Then we run:

nodemon app.js

to use it.

Fix ‘Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response’ Error with Express Apps

We can add the cors middleware to allow cross-origin requests.

Then this error should go away.

We can write:

const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.options('*', cors());

We use the cors middleware to add the Access-Control-Allow-Origin and Access-Control-Allow-Methods headers.

Also, we added the required OPTION routes with the cors middleware.

We allow all routes to accept OPTION requests with '*' .

Conclusion

There are several packages to read Excel files.

We can pass variables to templates with Express.

Also, we can write CSV easily to a file with a library.

To allow our Express app to listen for cross-origin requests, we need the cors middleware.

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 *