Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm a beginner of node.js and javascript.

I want to include external javascript file in html code. Here is the html code, "index.html":

<script src="simple.js"></script>

And, here is the javascript code, "simple.js":

document.write('Hello');

When I open the "index.html" directly on a web browser(e.g. Google Chrome), It works. ("Hello" message should be displayed on the screen.)

However, when I tried to open the "index.html" via node.js http server, It doesn't work. Here is the node.js file, "app.js":

var app = require('http').createServer(handler)
  , fs = require('fs')

app.listen(8000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

("index.html", "simple.js" and "app.js" are on same directory.) I started the http server. (by "bash$node app.js") After then, I tried to connect "localhost:8000". But, "Hello" message doesn't appear.

I think the "index.html" failed to include the "simple.js" on the http server.

How should I do?

share|improve this question
add comment

4 Answers

up vote 2 down vote accepted

The problem is that nomatter what your browser requests, you return "index.html". So the browser loads your page and get's html. That html includes your script tag, and the browser goes asking node for the script-file. However, your handler is set up to ignore what the request is for, so it just returns the html once more.

share|improve this answer
 
I got a direction by your advice. I need to learn about the 'handler'. Thanks! –  lancif Jul 18 '13 at 11:52
 
A quick tips. If you're using a reasonable browser, you should be able to see the requested and responded data fairly easily. Try clicking F12 in your browser, and look for something named "network" or "request" (or similar, depends on browser). –  Alxandr Jul 18 '13 at 11:59
add comment

Alxandr is right. I will try to clarify more his answer.

It happens that you have to write a "router" for your requests. Below it is a simple way to get it working. If you look forward www.nodebeginner.org you will find a way of build a proper router.

var fs = require("fs");
var http = require("http");
var url = require("url");

http.createServer(function (request, response) {

    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");

    response.writeHead(200);

    if(pathname == "/") {
        html = fs.readFileSync("index.html", "utf8");
        response.write(html);
    } else if (pathname == "/script.js") {
        script = fs.readFileSync("script.js", "utf8");
        response.write(script);
    }


    response.end();
}).listen(8888);

console.log("Listening to server on 8888...");
share|improve this answer
add comment

Your handler is hardcoded to always return the content of /index.html. You need to pay attention to the resource that is being requested and return the right one. (i.e. if the browser asks for simple.js then you need to give it simple.js instead of index.html).

share|improve this answer
add comment

Here is a working code. There should be more cleaner simpler code, but this is very close to minimal.

This code suppose your index.html and other files are under /client dir.

Good luck.

var fs = require('fs');
var url = require("url");
var path = require('path');
var mime = require('mime');

var log = console.log; 

var handler = function (req, res)
{
    var dir = "/client";
    var uri = url.parse(req.url).pathname;
    if (uri == "/")
    {
        uri = "index.html";
    }
    var filename = path.join(dir, uri);
    log(filename);
    log(mime.lookup(filename));
    fs.readFile(__dirname + filename,
        function (err, data)
        {
            if (err)
            {
                res.writeHead(500);
                return res.end('Error loading index.html');
            }
            log(data);
            log(filename + " has read");
            res.setHeader('content-type', mime.lookup(filename));
            res.writeHead(200);
            res.end(data);
        });
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.