You should take into account that nodejs often uses asyncronous calls, and this is the case with your code too.
fs.readFile('index.html', (err,html)=>{
if(err){
throw err;
}
console.log(html); // html works here
});
console.log(html); // html is undefined here
This should work
fs.readFile('index.html', (err,html)=>{
if(err){
throw err;
}
var server = http.createServer((req,res)=>{
res.statusCode = 200;
res.setHeader('Content-type','text/plain');
res.write(html);
res.end();
});
server.listen(port,host,() =>{
console.log('Server started with port: '+port);
});
});
On the other hand, I would not recommend writing your server like this, except for learning purposes. There are ready-made nodejs based frameworks that will take a lot of pain out of writing a good web server, like express or hapi
1
solved I am getting a ReferenceError: html is not defined