0

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?

2
  • 1
    You are returning index.html for every request. Commented Feb 22, 2018 at 19:56
  • Your code is only going to output the contents of ./index.html for all requests. There is going to be another request for /js/script.js and you have to return that. Look at the express.static in the express documentation. Commented Feb 22, 2018 at 19:56

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

3 Comments

express.static is built into express and does the job. There is no need to pull another implementation in.
Oh, I apologize. My brain registered this as using express, but it is not.
@Dave Exactly, with express this would be easier

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.