2

I need to read a .csv file and convert the csv file to json format and pass the json to frontend

which is the best way to read a csv file and convert to json

Here my code is:

fs.readFile(req.files.file.path, function(ferr, file) {
        if (ferr) {
            res.json(HttpStatus.NOT_FOUND, { error: ferr });
        }
        if (file) { //here i will get my file
            //here i need to write code for convert the csv file to json
}
1

1 Answer 1

1

Here's the code to read .csv file and print it in json format.

Firstly install CSV module To do so un the following command from the console:

npm install csv

Then create a file and use the following code

var csv = require('csv');
// loads the csv module referenced above.

var obj = csv();

// gets the csv module to access the required functionality
function MyCSV(name, number, id) {
    this.FieldOne = name;
    this.FieldTwo = number;
    this.FieldThree = id;
};
​
var MyData = [];

obj.from.path('../THEPATHINYOURPROJECT/TOTHE/csv_FILE_YOU_WANT_TO_LOAD.csv').to.array(function (data) {
    for (var index = 0; index < data.length; index++) {
        MyData.push(new MyCSV(data[index][0], data[index][1], data[index][2]));
    }
    console.log(MyData);
});

var http = require('http');
//Load the http module.
​
var server = http.createServer(function (req, resp) {
    resp.writeHead(200, { 'content-type': 'application/json' });
    resp.end(JSON.stringify(MyData));
});

server.listen(8080);

Once completed start your app using

Node app
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.