CSV File Format:
username,city
tony,new york
steve,washington dc
bruce,queens
clint,london
natasha,perth
tony,new york
steve,washington dc
bruce,queens
clint,london
natasha,perth
'use strict'; const http = require('http'); const fs = require('fs'); const csvp = require('csv-parser'); const cors = require('cors') const express = require('express'); const app = express(); const busboy = require('connect-busboy'); // A node.js module for parsing incoming HTML form data. const server = http.createServer(app); const port = 8084; app.use(busboy()); app.use(cors()); app.post('/file', function (req, res) { var fstream; let errors = []; req.pipe(req.busboy); req.busboy.on('file', function (fieldname, file, filename) { fstream = fs.createWriteStream('uploads/' + filename); file.pipe(fstream); fstream.on('close', function () { fs.createReadStream('uploads/test.csv') .pipe(csvp()) // { headers: false } to skip headers .on('data', (row) => { console.log("row", row); try { username = row.username; city = row.city; } catch (exception) { return res.status(400).json({ status: 400, data: exception, message: "Invalid CSV file" }); } }) .on('end', () => { if (errors.length > 0) { console.log("Errors", errors); return res.status(400).json({ status: 400, data: errors, message: "Invalid records in the csv file" }); } else { console.log("Success"); return res.status(200).json({ status: 200, data: {}, message: "File upload successfully" }); } }); }); }); }); // Start server function startServer() { server.listen(port, function () { console.log('Express server listening on ', port); }); } setImmediate(startServer);
No comments:
Post a Comment