NestJS CSV Parser

2.0.4 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `CsvModule` in a NestJS application, define a TypeScript entity to map CSV data, and use `CsvParser` to read and parse a CSV file stream into an array of typed objects. It includes creating a temporary CSV file for demonstration.

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();

view raw JSON →