csv-parse
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
The csv-parse package is a robust tool for parsing CSV text input into arrays or objects. Built for Node.js and the web, it implements the Node.js stream.Transform API, providing a combination of simplicity and power. Whether you're handling large datasets or small, csv-parse can be a versatile addition to your JavaScript toolset.
To use csv-parse, you'd start by installing the package with npm. If you're interested in the full CSV module, you can run npm install csv
. For just the CSV parser, use npm install csv-parse
. Once installed, csv-parse can be used with either a simpler callback-based API or a scalable stream-based API.
Here's an example of how to parse CSV data using the stream API:
import assert from 'assert';
import { parse } from 'csv-parse';
const records = [];
// Initialize the parser
const parser = parse({
delimiter: ':'
});
// Use the readable stream api to consume records
parser.on('readable', function(){
let record;
while ((record = parser.read()) !== null) {
records.push(record);
}
});
// Catch any error
parser.on('error', function(err){
console.error(err.message);
});
// Test that the parsed records matched the expected records
parser.on('end', function(){
assert.deepStrictEqual(
records,
[
[ 'root','x','0','0','root','/root','/bin/bash' ],
[ 'someone','x','1022','1022','','/home/someone','/bin/bash' ]
]
);
});
// Write data to the stream
parser.write("root:x:0:0:root:/root:/bin/bash\n");
parser.write("someone:x:1022:1022::/home/someone:/bin/bash\n");
// Close the readable stream
parser.end();
In this case, the parser is reading data with ':' as a delimiter.
You can find comprehensive documentation for csv-parse on its project homepage (https://csv.js.org/parse/). Here links are provided for specific sections, including the API (https://csv.js.org/parse/api/), a guide to options (https://csv.js.org/parse/options/), info properties (https://csv.js.org/parse/info/), common errors (https://csv.js.org/parse/errors/), and a collection of examples (https://csv.js.org/project/examples/) to help you get started.