NestJS CSV Parser
nest-csv-parser is a utility module designed for the NestJS framework, simplifying the process of parsing CSV files within server-side applications. It acts as a lightweight wrapper around the popular `csv-parser` library, exposing its functionality in a NestJS-idiomatic way through an injectable service. The current stable version is 2.0.4. While a strict release cadence isn't explicitly stated, the project appears actively maintained given its version history and documentation. Its primary differentiator is seamless integration into NestJS applications using `@Module` imports and dependency injection, allowing developers to consume CSV data streams and map them directly to TypeScript entities with optional control over line counts, offsets, and underlying `csv-parser` configurations. It handles streaming large files efficiently without loading the entire content into memory.
Common errors
-
Nest can't resolve dependencies of the CsvParser (?). Please make sure that the argument at index [0] is available in the CsvModule context.
cause The `CsvModule` has not been correctly imported into the `imports` array of the module where `CsvParser` is being injected, or the module providing `CsvModule` is not imported into the current module.fixAdd `CsvModule` to the `imports` array of the NestJS module where you are using `CsvParser`. For example: `@Module({ imports: [CsvModule], providers: [...] })`. -
Property 'parse' does not exist on type 'CsvParser'.
cause This error typically occurs if TypeScript cannot infer the type of `csvParser` or if an older version of the package is used that might have a different API. More commonly, it means `CsvParser` was not properly injected or imported.fixEnsure `CsvParser` is correctly injected via the constructor (`private readonly csvParser: CsvParser`), and that `import { CsvParser } from 'nest-csv-parser'` is present at the top of the file.
Warnings
- gotcha The `csv-parser` library (which `nest-csv-parser` wraps) expects CSV headers to exactly match the property names of your TypeScript `Entity` class. Mismatches will result in `undefined` values for those properties.
- gotcha By default, `nest-csv-parser` configures the underlying `csv-parser` with `{ strict: true, separator: ';' }`. If your CSV uses a different separator (e.g., comma `,`) or has inconsistent row lengths, you must override `csvConfig` in the `parse` method.
- gotcha The `parse` method returns a `Promise<Entity[]>`. It's crucial to `await` this promise, especially when dealing with potentially large files, to ensure all data is processed before attempting to use the results. Forgetting `await` will result in a promise object instead of the parsed data.
Install
-
npm install nest-csv-parser -
yarn add nest-csv-parser -
pnpm add nest-csv-parser
Imports
- CsvModule
import CsvModule from 'nest-csv-parser'
import { CsvModule } from 'nest-csv-parser' - CsvParser
const { CsvParser } = require('nest-csv-parser')import { CsvParser } from 'nest-csv-parser' - Injectable
import { Injectable } from 'nest-csv-parser'import { Injectable } from '@nestjs/common'
Quickstart
import { Module, Injectable } from '@nestjs/common';
import { CsvModule, CsvParser } from 'nest-csv-parser';
import * as fs from 'fs';
// 1. Define your entity structure matching CSV headers
class MyDataEntity {
id: number;
name: string;
value: string;
}
@Injectable()
export class MyCsvService {
constructor(
private readonly csvParser: CsvParser
) {}
async parseMyCsvFile(): Promise<MyDataEntity[]> {
// Create a dummy CSV file for demonstration
const csvContent = 'id,name,value\n1,Alice,Alpha\n2,Bob,Beta\n3,Charlie,Gamma';
const filePath = './temp.csv';
fs.writeFileSync(filePath, csvContent);
// Create a readable stream from the file
const stream = fs.createReadStream(filePath);
try {
// Parse the stream into an array of MyDataEntity objects
const entities: MyDataEntity[] = await this.csvParser.parse(stream, MyDataEntity);
console.log('Parsed Entities:', entities);
return entities;
} finally {
// Clean up the dummy file
fs.unlinkSync(filePath);
}
}
}
@Module({
imports: [CsvModule],
providers: [MyCsvService],
exports: [MyCsvService]
})
export class MyCsvParsingModule {}
// Example of how to use it (e.g., in your main.ts or another module)
async function bootstrap() {
// In a real NestJS app, this would be handled by the framework
// For quickstart, we'll manually instantiate
const moduleRef = await import('@nestjs/core').then(m => m.NestFactory.createApplicationContext(MyCsvParsingModule));
const myCsvService = moduleRef.get(MyCsvService);
await myCsvService.parseMyCsvFile();
await moduleRef.close();
}
bootstrap();