Welcome folks today in this blog post we will be using the csv-string
library to parse
and validate
csv strings in command line using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new node.js
project using the below command as shown below
npm init -y
npm i csv-string
And after that you need to make a new index.js
file and copy paste the following code.
Parse CSV Strings
Now first of all we will be parsing csv strings
using some delimiter
such as comma or semicolon as shown below
index.js
1 2 3 4 5 |
const CSV = require('csv-string'); const parsedCsv = CSV.parse('a;b;c\nd;e;f', ';'); console.log(parsedCsv); |
As you can see we are importing the csv-string
library and then we are using the parse()
method to provide the csv
string and then here we are parsing by semicolon
delimiter to construct the csv string as shown below
And we can even output objects
as well by providing the additional property as shown below
1 2 3 |
const CSV = require('csv-string'); const parsedCsv = CSV.parse('a,b,c\n1,2,3\n4,5,6', { output: 'objects' }); console.log(parsedCsv); |
Validating CSV Strings
Now we can even validate csv
strings and find the delimiters
of the csv strings as shown below
index.js
1 2 3 4 5 6 |
const CSV = require('csv-string'); console.log(CSV.detect('a,b,c')); console.log(CSV.detect('a;b;c')); console.log(CSV.detect('a|b|c')); console.log(CSV.detect('a\tb\tc')); |