Exercise 1: Solution
File system read: async read.
"Node style callbacks": first argument is err, second is a file buffer (for
In fact with Express you don't even need to read the file yourself, just use:
res.sendFile(__dirname + '/index.html', function(err){...});
set the status code :
res.status(500).send(err)
(though not recommended this example, 500 on an index page)fileRead
)To convert the buffer from
fileRead
:var html = buffer.toString()
var express, app, jsonData, fs...
app.get('/', function(req,res){
fs.readFile('index.html', function(err, buffer){
var html = buffer.toString();
res.setHeader('Content-Type', 'text/html');
res.send(html);
})
})
app.listen(3000)
- to stream the contents of the file?- this example fires when the complete file is read (doesn't give more details)
How to restart NodeJS?$ npm install -g nodemon
it will restart the server when do a change to a file and save it.