Eugene Kostrikov Eugene Kostrikov - 2 months ago 12
Node.js Question

Read a file in Node.js

I'm quite puzzled with reading files in Node.js.

fs.open('./start.html', 'r', function(err, fileToRead){
if (!err){
fs.readFile(fileToRead, {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);
}
});
}else{
console.log(err);
}
});


File
start.html
is in the same directory with file that tries to open and read it.

However, in the console I get:


{ [Error: ENOENT, open './start.html'] errno: 34, code: 'ENOENT', path: './start.html' }


Any ideas?

Answer

Use path.join(__dirname, '/start.html');

var fs = require('fs');
var path = require('path');

var 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.