Receive and Parse a CSV file with NestJs — Part 1

Wahyu Endy Santoso
3 min readDec 26, 2021

--

If you learn typescript I think you are not a stranger anymore with NestJs, this is a powerful tool to help us develop a backend project. In this article we will try to receive a CSV file and parse it before storing it

In the first time, we need to generate our project, we can doing that with run.

nest new project_na

This command will help us to auto-generate our project.

With NestJs we can separate our modules & make them modular, this is helpful when we work on large projects to simplify our code structure. And Nestjs already provide a few terminal commands to create modules, controller, service, etc.

To make it easier, we only create and use module & controller

npx @nestjs/cli g module assetnpx @nestjs/cli g controller asset

In NestJs , we place all routers in our controller. But before doing that, we need to import the HTTP method decorators from Nestjs

We can do our job with a many ways, but in our case, we will do like this

1. Take a file, with a FileInterceptor

2. Save it into our local directory, with diskStorage

3. Read the file in local directory

4. Parse it

5. Store it

FileInterceptor is a built-in decorators from @nestjs/platform-express, we use this to receive the file from front end or postman, but we need to decide a name property used. In our example we use the “file_assetname

postman

Now our server is ready to receive the file, we continue to save it into our local directory. To do that, we use the diskStorage from multer

The disk storage engine gives you full control on storing files to disk.

code

When use diskStorage, we need to set a destination path for storing a files with destination property. With a combination of FileInterceptor and diskStorage our controller will looks like this.

we finished our code for step 1 and 2, next we will read a new file that sent into our server with readFileSync from fs package.

readFileSync will help us to reads the entire contents of a file, we just need a directory path of the file

read file with readFileSync method

to parse the CSV file, there one really helpful package to do that. The name is papaparse, and we just need a parse method

parse the csv file with papaparse

Nice Job to you 👍, until this process, our server can receive the CSV file & parse that data. We will continue to part 2 article to store to the Firebase.

I be back soon

--

--