jgozal jgozal - 1 year ago 74
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.');

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
but I do not wish to use
. I am trying to learn how things work behind the scene. Thanks in advance.

Answer Source

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() {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download