Showing posts with label nodejs. Show all posts
Showing posts with label nodejs. Show all posts

Monday, 24 August 2020

File upload and parse in Node JS

CSV File Format:

username,city
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);

Sunday, 29 December 2019

What is Node JS and how it works

What is Node JS? 

Node is a open source and cross platform run time environment for executing JavaScript code outside of a browser, so basically node server executes the JavaScript code, not the browser. 

Node run time uses V8 engine and C++ program to execute JavaScript. 

How Node Works? 

  • Node applications are asynchronous by default. 
  • Node uses a single thread to handle all the requests. When the requests arrives, that single thread is used to handle all those. 
  • Node JS platform uses Single Threaded Event Loop model.

Example: 

“If we send a request to database, the thread doesn’t have to wait for the database to return the data. While database is executing query same thread will be used to serve another request. When the database returns the result it puts a message in the Event Queue. Node continuously monitors this event queue in background and when it finds an event in the queue it takes it and process it”.