2

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': 'text/plain'
    });
    res.write("Hello!");
    res.end();
}).listen(8080);

I put this code in WebStorm and ran it. Then I put in the same directory index.html file.

<body>
    <button id="btn">Click Me</button>
    <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
    <script src="requester.js"></script>
</body>

I also put requester.js file in the same folder.

$('#btn').on("click", function () {
    $.get('/', function () {
        console.log('Successful.');
    });
});

Then I execute command live-server in this folder where all files are. I don't know how to make the server to work on localhost. Thank you in advance.

3
  • You havent shown any effort to actually send the file to the user. Have a look at expressjs.com, especially their .static method... Commented Sep 10, 2017 at 13:39
  • I need to do this only with http module. Is it possible? Commented Sep 10, 2017 at 13:42
  • Yes. Have a look at .sendFile, fs.readFile, Streams. Commented Sep 10, 2017 at 13:43

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.