Skip to content Skip to sidebar Skip to footer

Running Node Js Server On Localhost

I want to make a very simple web server like this for example. const http = require('http'); http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type

Solution 1:

You want to send your index.html file instead of the string "Hello":

const http = require('http');
const fs = require('fs');
const path = require('path');

http.createServer(function (req, res) {
    //NOTE: This assumes your index.html file is in the // .    same location as your root application.const filePath = path.join(__dirname, 'index.html');
    const stat = fs.statSync(filePath);

    res.writeHead(200, {
        'Content-Type': 'text/html',
        'Content-Length': stat.size
    });

    var stream = fs.createReadStream(filePath);
    stream.pipe(res);
}).listen(8080);

Depending on the complexity of your server in the future, you may want to investigate express as an alternative to the built-in http module.

Post a Comment for "Running Node Js Server On Localhost"