Guilherme Marques
Guilherme Marques

Reputation: 75

Can't access JavaScript static file through HTML using Node.js

I'm using a Node.js server to show an HTML file. The HTML uses a Javascript file to get some info but I'm not being able to access that file. Here's my index.html file:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Swarm Profile</title>
    </style>
  </head>
  <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="/js/script.js"></script>
  </body>
</html>

And my Node.js server file:

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

const hostname = '127.0.0.1';
const port = 9000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/html');
  fs.createReadStream("./index.html").pipe(res);
});


server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

What should I use to be able to access the script.js file?

Upvotes: 0

Views: 84

Answers (1)

Guilherme Holtz
Guilherme Holtz

Reputation: 485

There are many static file handler modules already in node, take a look at: Node static modules

Most popular are: Node-Paperboy and Node-Static

Using node static is as simple as:

var static = require('node-static');
var file = new(static.Server)('./public');

require('http').createServer(function (request, response) {
    request.addListener('end', function () {

        file.serve(request, response);
    });
}).listen(8080);

Upvotes: 4

Related Questions