2

I want to read a csv file and whenever someone connects to my server it prints the content of the file in their browser.

I have this module called 'lecture_csv' that lets me read the file and directly print it in the terminal:

var csv = require('csv-parser')
var fs = require('fs')


function lecture_csv(fileName) {
    fs.createReadStream(fileName)
    .pipe(csv())
    .on('data', (row) => {
    //console.log(row)
    return row;
    })
    .on('end', () => {
    console.log('fichier lu');
    });  
}

exports.lecture_csv = lecture_csv

What I want is to print 'row' on the client browser.

However in my main:

let lecture = require('./lecture_csv');
var http = require('http');
//let app = require('./app');

var fileName = 'test_file.csv'
var string = ''
//lecture.lecture_csv(fileName);

http.createServer(function(req, res){
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write(lecture.lecture_csv(fileName));
  res.end();
}).listen(9000);

I have an error saying I can't use res.write as the parameter in undefined instead of a string. Is there a way to get 'row' and print it on the client browser?

I am still very new to nodejs therefore any tips is welcomed.

1 Answer 1

1

You have to read file and send its contents ,like below

let lecture = require('./lecture_csv');
let fs=require("fs");
var http = require('http');
var fileName = './test_file.csv'
var string = ''
//lecture.lecture_csv(fileName);

http.createServer(function(req, res){

   fs.readFile(fileName, 'utf8', function(err, contents) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
     res.write(contents);
     res.end();
});

}).listen(9000);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your solution, the only detail was to exchange 'lecture' with 'fileName' in the fs.readFile().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.