2K01B5
2K01B5

Reputation: 1121

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)

Upvotes: 0

Views: 2541

Answers (1)

Viktor Sarstr&#246;m
Viktor Sarstr&#246;m

Reputation: 510

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();
    }
  });
});

Upvotes: 4

Related Questions