简体   繁体   中英

Serving Up a Javascript file using Node.js

I'm trying to serve up some static files using an extremely basic node.js server. The aim is to serve a html file with a script tag referencing a javascript file. When opening the application in the browser the html renders fine, the problem is with the js file. In the browser the js file has the html code in it and not the js code.

SERVERC CODE:

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

var port = 3000;

var app = http.createServer(function(req, res){
    var html = fs.createReadStream('./index.html')

    html.pipe(res);
})

app.listen(port, function(){
    console.log('Listening on port ' + port)
})

HTML CODE(index.html):

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Hello</title>
 </head>
 <body>
  <h1>Hello</h1>
  <script src="./some.js"></script>
 </body>
</html>

JAVASCRIPT CODE(some.js):

console.log("Hello")

DIRECTORY STRUCTURE:

|-index.html
|-some.js
|-app.js(server)

I would advise you to create a directory for the files that you need to serve in the following manner

|-public
    |-index.html
    |-some.js
|-app.js(server)

Then you use express.static to serve that directory you created.

var express = require('express');
var app = express();
var path = require('path');
var port = 3000;

app.use(express.static(path.join(__dirname, 'public')));

app.listen(port, function(){
   console.log('Listening on port ' + port)
})

Then you just run

node app.js

Without using express you can do the following

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

http.createServer(function (request, response) {

    var filePath = '.' + request.url;
    if (filePath == './')
       filePath = './index.html';

    var extName = path.extname(filePath);
    var contentType = 'text/html';
    switch (extName) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    path.exists(filePath, function(exists) {

    if (exists) {
        fs.readFile(filePath, function(error, content) {
            if (error) {
                response.writeHead(500);
                response.end();
            }
            else {
                response.writeHead(200, { 'Content-Type': contentType });
                response.end(content, 'utf-8');
            }
        });
    }
    else {
        response.writeHead(404);
        response.end();
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM