-4

I am new to Node.js and this is my first time using Node.js. When I tried to connect my index.html file I am getting this 'ReferenceError: html is not defined' error. This is my index.js code

var http = require('http');
var fs = require('fs');
var port = 3030;
var host = '127.0.0.1';

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);
});

This is my index.html code,

`<html>
    <body>
        <h1>Node JS</h1>
    </body>
</html>

The error I got,

 res.write(html);          
           ^

ReferenceError: html is not defined
    at Server.http.createServer 
(C:\Users\manee\OneDrive\Documents\Nodejs\index.js:15:15)
    at emitTwo (events.js:126:13)
    at Server.emit (events.js:214:7)
    at parserOnIncoming (_http_server.js:602:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)

If someone could tell Why I am getting this error, and am I missed anyting, that would be really great. Thank You

maneesha
  • 145
  • 2
  • 4
  • 12

2 Answers2

1

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

Akasha
  • 2,162
  • 1
  • 29
  • 47
0

In node js your server is trying to return the file before reading it from the disk. this is the basic nature of node js callback.

var server = http.createServer((req,res)=>{
    res.statusCode = 200;
    res.setHeader('Content-type','text/plain');
    fs.readFile('index.html', (err,html)=>{
    if(err){
        throw err;
    }
        res.write(html);
        res.end();
    });

});
Vora Ankit
  • 682
  • 5
  • 8