Deke
Deke

Reputation: 4649

Loading javascript file in node?

I'm configuring a very basic server with node(without express). I have a html file which has a link to javascript file. Right now I'm able to load only the html file and not the js resource to it. how to load the js file?

server.js

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

var scriptFile = path.join(__dirname), '/script.js')

http.createServer(function(req, res) {
 if (req.url === '/') {
   fs.readFile('./index.html', function(err, data) {
     if (err){
      throw err;
     }
     res.writeHead(200, {"Content-Type": 'text/html'});
     res.write(data); 
     fs.readFileSync(path.normalize(scriptFile)) //throws error here. script file when html page is loaded. 
//i'm trying to load the script.js when html file is loaded
     res.end();
     return;
   });
  }
}).listen(3000);

html:

<body>
 <h1> Hi </h1>
 <script src="script.js">
</body>

Upvotes: 1

Views: 4578

Answers (2)

Ashen Gunaratne
Ashen Gunaratne

Reputation: 455

The response for route /script should be handled differently as pointed out by @David moreover consider utilising Node.js streams for robustness

const fs = require('fs');
const http = require('http');

http.createServer(function (req, res) {

  if (req.url === '/') {
    fs.createReadStream('index.html').pipe(res);
    return;
  }

  if (req.url === '/script.js') {
    fs.createReadStream('script.js').pipe(res);
    return;
  }

}).listen(3000);

Additionally, it declutters the source code!

Upvotes: 2

David
David

Reputation: 144

When your browser requests index.html it will read through the HTML and find that it references your script file in the <script> tag. When the browser sees these it makes an additional request to the server. So, to serve up other files, you just have to handle requests for those routes. I modified your example to demonstrate this:

server.js

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

http.createServer(function(req, res) {
    if (req.url === '/') {
        fs.readFile('./index.html', function(err, data) {
            if (err){
                throw err;
            }
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.write(data); 
            res.end();
            return;
        });
    } else if (req.url === '/script.js') {
        fs.readFile('./script.js', function (err, data) {
            if (err) { throw err; }
            res.writeHead(200, { 'Content-Type': 'text/javascript' });
            res.write(data);
            res.end();
            return;
        });
    }
}).listen(3000);

index.html

<html>
    <head>
        <title></title>
    </head>
    <body>
        <h1> Hi </h1>
        <!-- Your browser will see this and then make an additional HTTP GET request for /script.js -->
        <script src="script.js"></script>
    </body>
</html>

You can verify this behavior using Chrome Developer tools.

  1. Open developer tools by choosing the three-dot menu in the upper right-hand corner, and choosing More Tools -> Developer Tools.
  2. Go to the network tab.
  3. Navigate to localhost:3000 (or just refresh your page).

You'll see that two requests are made. The first is for index.html and then the second will be for the script referenced in the script tag.

Upvotes: 2

Related Questions