How to include javascript on client side of node.js?

后端 未结 5 1365
南笙
南笙 2020-11-30 05:25

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\":



        
5条回答
  •  孤独总比滥情好
    2020-11-30 06:00

    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...");
    

提交回复
热议问题