Read a file in Node.js
1).For ASync :
var fs = require('fs');
fs.readFile(process.cwd()+"\\text.txt", function(err,data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
2).For Sync :
var fs = require('fs');
var path = process.cwd();
var buffer = fs.readFileSync(path + "\\text.txt");
console.log(buffer.toString());
Use path.join(__dirname, '/start.html')
;
var fs = require('fs'),
path = require('path'),
filePath = path.join(__dirname, 'start.html');
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
if (!err) {
console.log('received data: ' + data);
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
} else {
console.log(err);
}
});
Thanks to dc5.
With Node 0.12, it's possible to do this synchronously now:
var fs = require('fs');
var path = require('path');
// Buffer mydata
var BUFFER = bufferFile('../public/mydata.png');
function bufferFile(relPath) {
return fs.readFileSync(path.join(__dirname, relPath)); // zzzz....
}
fs
is the file system. readFileSync() returns a Buffer, or string if you ask.
fs
correctly assumes relative paths are a security issue. path
is a work-around.
To load as a string, specify the encoding:
return fs.readFileSync(path,{ encoding: 'utf8' });