CSV to JSON is most common task we developer do, and there are many open source nodejs package to do this job.
-
Now make a folder in the project app/data and save the your csv files there.
-
I was using csv-parser package, install this first.
terminal
Copynpm install csv-parser
- Open server.js file and add two lines in this file.
JavaScript
Copy// server.js const csvParserRoutes = require('./app/routes/csvParserRoutes'); app.use('/csv', csvParserRoutes);
- Create a route file in the app/routes directory named csvParserRoutes.js
JavaScript
Copy// app/routes/csvParserRoutes.js const express = require('express'); const router = express.Router(); const csvParserController = require('../controllers/csvParserController'); router.get('/parse', csvParserController.parseCsv); module.exports = router;
- Create a controller file in the app/controllers directory named geoController.js
JavaScript
Copy// app/controllers/csvParserController.js const csv = require('csv-parser'); const path = require('path'); const fs = require('fs'); const { responseList } = require('../errors/responseList'); const csvFile = path.join(__dirname, '../data/dummy.csv'); async function csvToJson(csvFilePath) { const jsonArray = []; return new Promise((resolve, reject) => { fs.createReadStream(csvFilePath) .pipe(csv()) .on('data', (data) => jsonArray.push(data)) .on('end', () => { resolve(jsonArray); }) .on('error', (error) => { reject(error); }); }); } exports.parseCsv = async (req, res) => { try { const jsonArray = await csvToJson(csvFile); res.status(200).send(jsonArray); } catch (error) { res.status(500).send(responseList(500, error.message)); } };
Now your API endpoint is ready and can test like this.
terminal
Copyhttp://localhost:3001/csv/parse
And you can deploy this on DigitalOcean, Render, & Also on Glitch.