jgozal jgozal - 2 months ago 6
HTTP Question

making js and other files available to html via node.js http server

I have a very simple web server like this:

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {

res.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('./index.html', 'utf-8', function (err, content) {
if (err) {
res.end('something went wrong.');
return;
}
res.end(content);
});

}).listen(8080);
console.log("Server running on port 8080.")


This renders my index.html without any issues, but if I try to reference another file in my index.html via a script tag for instance, the site just gets stuck, unable to find the file which exists in the server directory.

How can I make those files available to my index.html file?

Please keep in mind that I realize this can be done much more easily with
Express
but I do not wish to use
Express
. I am trying to learn how things work behind the scene. Thanks in advance.

Answer

You need to make the directory visible to public. Its is recommend to use framework while developing the Node.js application.

Here is the code below to server file without framework.

var basePath = __dirname;
var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function(req, res) {
    var stream = fs.createReadStream(path.join(basePath, req.url));
    stream.on('error', function() {
        res.writeHead(404);
        res.end();
    });
    stream.pipe(res);
}).listen(9999);

Refer : Node itself can serve static files without express or any other module..?