1

Im tryin to make an API with a single endpoint which receives a csv file and convert it contents into a json array.

Im using NestJs and I got how to upload a file using Postman

this is my controller

@Controller('csv')

export class CsvController {

constructor(private csvService: CsvService) {}

@Post()
@UseInterceptors(FileInterceptor('file'))
async uploadFile(@UploadedFile() file: any, @Res() res) {
    console.log(file)
    //this is the service which Im trying to use to convert into json array
    const resp = await this.csvService.parse(file)

    res.send(file.buffer) //this just return the csv content
}

}

At service I added the library nest-csv-parser but it needs a stream type, the stream type needs a file location. So I have no idea how to convert a CSV file received from Postman, and not dropping it into my project.

 constructor(private readonly csvParser: CsvParser) {}

async parse(stream: any) {
    const str = createReadStream(stream)

    const entities: any = await this.csvParser.parse(
        str,
        Person
    )

    console.log(entities)
}

Any ideas about what can I do ?

If I miss somth just let me know!

Nehlk
  • 31
  • 1
  • 4

1 Answers1

2

I doubt that the file you get from that endpoint is a buffer. So you need to turn buffer to stream before using csv parser. For turning buffer to stream, using Readable stream from turning buffer to stream using NodeJS

deko_39
  • 68
  • 7