
#Nodejs readline code#
In your readCSV2.js file, add the following code to import the fs and the readline module The readLine module provides an interface for reading data line by line. This can be avoided by reading the file line by line. Sooner or later, you will run out of memory. You may have noticed the shortcoming of reading the entire CSV file at once.
#Nodejs readline how to#
To create columns, you will need a loop that will traverse through the data array and split the comma-separated values into individual columns(fields).ĪLSO READ: How to get all files in directory in Node.js Method-2: Read the CSV File Line by Line

In this code, we are using a regular expression to split the data string at a new line which essentially creates an array of rows (records).

Consider the code below: data = data.split(/\r?\n/) You will then split the data into rows which will then be split into columns. Let data = fs.readFileSync("./csvsample.csv", "utf8") Passing in the UTF-8 encoding option returns the file content as a string and not a buffer. The next step is to read the entire file as a string using the readFileSync command which returns the content of the file passed. The file system module will help you interact with other files, in this case, the file with the sample data. To get started, create a file called readCSV1.js and import the file system module. In this method, you will read the entire file as a string and then split it into rows and columns. Method-1: Read the entire CSV file as a string You can parse a CSV file using different methods. READ: 2 ways to get POST body data in Express with Examples Parsing CSV Data You can choose to generate your own or copy the following. We will be using mockaroo to generate some random data. Start by initializing your NodeJs project by generating a package.json file by running the following command.Ĭreate a new file and call it, `csvsample.csv`.This will be the file containing the CSV sample data. To better understand this article and follow along with the example, you should have prior knowledge of JavaScript concepts and at least Node 8 installed.

By the end, you will be able to read and write CSV files. In this article, you will learn how to parse CSV files in NodeJS. One of the most common uses of CSV files is to import and export data. The records have values separated by commas that represent fields. CSV files store tabular data where each of the lines in the file represents a record.
