Reputation: 59
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.
Upvotes: 2
Views: 913
Reputation: 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);
Upvotes: 1