Nodejs Script to Add Rows in CSV File Through Terminal

Filling out a CSV file through Office Excel or LibreOffice Calc is easy enough, but you may find it quicker to type in fields on a terminal, particularly when you want to process the data before entry, use defaults, or keep the entry process totally mouse-free.

So let’s write a nodejs script that will start an interactive terminal session that takes info and saves it as a row in a CSV file.

Todos Before Code

  • Create an empty directory csvAdder; on terminal move to this directory.

  • With the help of Office Excel or LibreOffice Calc create a CSV file, fill in the headers, select the last header (because new row will come on new line), and save. Our example file is student.csv, and the headers are First Name, Last Name, Age, and Enrollment Date.

  • We only need two libraries. One is fs, that comes with nodejs. The other is inquirer, which we need to install, and which is required for the interactive session we want. Install it as npm i inquirer --save

Code

Now add a file add.js to the same directory, and paste the below code:

const fs = require('fs');
const inquirer = require('inquirer');

const d = new Date();

const data = [{
  type: 'input',
  name: 'First Name',
  message: "Enter First Name",
},
{
  type: 'input',
  name: 'Last Name',
  message: "Enter Last Name",
},
{
  type: 'number',
  name: 'Age',
  message: "Enter Age",
},
{
  type: 'input',
  name: 'Enrollment Date',
  message: "Enter Enrollment Date (leave empty for default)",
  default: `${d.getFullYear()}/${d.getMonth()}/${d.getDate()}`
}
];


function dataEntry() {
  console.log("Add a new row info or press Ctrl+C to exit the script")
  inquirer.prompt(data).then(entry => {
    fs.appendFile('students.csv', `${capitalize(entry['First Name'])}, ${capitalize(entry['Last Name'])}, ${entry['Age']}, ${entry['Enrollment Date']}\n`, function (err) {
      if (err) throw err;
      console.log('Saved!');
      dataEntry();
    });
  });
}
dataEntry();

function capitalize(str = "") {
  const lower = str;
  return lower.charAt(0).toUpperCase() + lower.substring(1);
}

Code Explained

  • d has the current date.

  • inquirer an object, with type, name, message etc. for each field. So we pass 4 in our case. Age is number, and Enrollment Date has the date of script running as default, in YYYY/MM/DD format.

  • dataEntry function is called.

  • Inside dataEntry we inform the user that they can do data entry or press Ctrl + C to exit the script.

  • inquirer takes over, and when user has entered all the fields it returns them as entry.

  • We use fs.appendFile to append those values as a row. We capitalize the first and last names entered. We also add \n so that the next record comes in new line.

  • dataEntry function is called again by itself. And the code runs indefinitely until the user exits.

csv  script 

See also