Reputation: 91949
I want to read a file and return is as a response to GET
request
This is what I am doing
app.get('/', function (request, response) {
fs.readFileSync('./index.html', 'utf8', function (err, data) {
if (err) {
return 'some issue on reading file';
}
var buffer = new Buffer(data, 'utf8');
console.log(buffer.toString());
response.send(buffer.toString());
});
});
index.html
is
hello world!
When I load page localhost:5000
, the page spins and nothing happens, what is I am doing incorrect here
I am newbie to Node.
Upvotes: 0
Views: 177
Reputation: 165941
You're using the synchronous version of the readFile
method. If that's what you intended, don't pass it a callback. It returns a string (if you pass an encoding):
app.get('/', function (request, response) {
response.send(fs.readFileSync('./index.html', 'utf8'));
});
Alternatively (and generally more appropriately) you can use the asynchronous method (and get rid of the encoding, since you appear to be expecting a Buffer
):
app.get('/', function (request, response) {
fs.readFile('./index.html', { encoding: 'utf8' }, function (err, data) {
// In here, `data` is a string containing the contents of the file
});
});
Upvotes: 3