Quick Examples
Quick examples of parsing and formatting.
Formatting
- TypeScript
- JavaScript
- Output
import * as csv from 'fast-csv';
const csvStream = csv.format({ headers: true });
csvStream.pipe(process.stdout).on('end', () => process.exit());
csvStream.write({ header1: 'row1-col1', header2: 'row1-col2' });
csvStream.write({ header1: 'row2-col1', header2: 'row2-col2' });
csvStream.write({ header1: 'row3-col1', header2: 'row3-col2' });
csvStream.write({ header1: 'row4-col1', header2: 'row4-col2' });
csvStream.write({ header1: 'row5-col1', header2: 'row5-col2' });
csvStream.end();
Parsing
- TypeScript
- JavaScript
- Output
import * as fs from 'fs';
import * as path from 'path';
import * as csv from 'fast-csv';
fs.createReadStream(path.resolve(__dirname, 'assets', 'parse.csv'))
.pipe(csv.parse({ headers: true }))
.on('error', error => console.error(error))
.on('data', row => console.log(row))
.on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`));
Parse And Format
- TypeScript
- JavaScript
- Output
import * as fs from 'fs';
import * as path from 'path';
import * as csv from 'fast-csv';
import { User } from './models/user';
interface UserCsvRow {
id: string;
first_name: string;
last_name: string;
address: string;
}
interface UserDetailsRow {
id: number;
firstName: string;
lastName: string;
address: string;
// properties from user
isVerified: boolean;
hasLoggedIn: boolean;
age: number;
}
fs.createReadStream(path.resolve(__dirname, 'assets', 'snake_case_users.csv'))
.pipe(csv.parse({ headers: true }))
// pipe the parsed input into a csv formatter
.pipe(
csv.format<UserCsvRow, UserDetailsRow>({ headers: true }),
)
// Using the transform function from the formatting stream
.transform((row, next): void => {
User.findById(+row.id, (err, user) => {
if (err) {
return next(err);
}
if (!user) {
return next(new Error(`Unable to find user for ${row.id}`);
}
return next(null, {
id: user.id,
firstName: row.first_name,
lastName: row.last_name,
address: row.address,
// properties from user
isVerified: user.isVerified,
hasLoggedIn: user.hasLoggedIn,
age: user.age,
});
});
})
.pipe(process.stdout)
.on('end', () => process.exit());