Node js read file
Path.join is used to create the file path. There is a directory "files" in the root of the project, where a "test.csv" file is stored. We handle file reading asynchronous.
var path = require('path');
var fs = require('fs');
var filePath = path.join(__dirname, 'files', 'test.csv');
fs.readFile(filePath, 'utf-8', function (err, data) {
if (err) {
return console.log("Unable to read file " + err);
}
console.log(data + '\n');
});
We can choose to write the filename in the console. The readline module allows us to get user input.
var fs = require('fs');
var readline = require('readline');
/*
* We need to create a readline interface.
* The interface takes 2 streams.
* The input field points to the readable input stream
* and the output field to the writable output stream.
*/
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('File path: ', function (filePath) {
fs.readFile(filePath, 'utf-8', function (err, data) {
if (err) {
return console.log("Unable to read file " + err);
}
console.log(data + '\n');
});
rl.close();
process.stdin.destroy();
});
You're not supposed to write synchronous javascript, so never use it, but if you want to see the synchronous version of reading a file in node:
var path = require('path');
var fs = require('fs');
var filePath = path.join(__dirname, 'files', 'test.csv');
var file = fs.readFileSync(filePath, 'utf-8');
console.log(file);