javascript not loading in HTML file - nodejs + http

load file css js in node js
js file not loading in html
javascript in separate file not working
javascript not executing in html
how to call html file in node js
node js html example
how to include node.js in html
getting data from node js file and displaying it in html/js page

Disclaimer: I am new to node.js so I assume there is a very basic answer to this question.

I am using node.js on Windows, with http module to generate a static page with content generate from a js file.

Server file (server.js):

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

fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err;
    }
    http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
        response.end();
    }).listen(8080);
});

HTML file (index.html):

<!DOCTYPE html>
<html>

<body>

<div id="div1">
  <p id="p1">This is a static paragraph.</p>
</div>

<p>
  <script type="text/javascript" src="start.js"></script>
</p>

</body>
</html>

JS file (start.js)

var para = document.createElement("p");
var node = document.createTextNode("This text is loaded from a js file.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);

When I load index.html directly, I get the following output:

This is a static paragraph.

This text is loaded from a js file.

^^ this is my desired output.

Problem: However, when I use node.js and run server.js, the start.js content does not load. I get:

This is a static paragraph.

Any help would be appreciated.

FYI, my folder structure

/
- node_modules
-- http
-- fs
- index.html
- server.js
- start.js

Your logic for appending child nodes seems okay.

I think you should try changing your src="start.js" to src="./start.js" or src="/start.js" just to make sure that you're referencing the path properly. Add a console.log() statement in your start.js to make sure that it is being loaded.

EDIT: Make sure you are hosting your file on your server. You could add something like express or connect to help.

To use connect, run npm install --save connect in your project directory.

var connect = require('connect'),
directory = '/path/to/Folder'; // probably just '/' for all your files

connect()
  .use(connect.static(directory))
  .listen(80);

console.log('Listening on port 80.');

Refer to their docs for full instructions and more examples using http.

Javascript file is not working with HTML - Get Started, Javascript file is not working with HTML My recommendation is to install node js and use the http-server package to run a local server on your  Javascript file is not working with HTML. Get Started. is the file not loading at My recommendation is to install node js and use the http-server package to run a local server on your

Every request url that you get for a file needs to be handled by the node server. I would suggest using Express.js as this would ease in handling the different url paths and files can be served directly. But in case you want a pure node.js based implementation, check below code.

To serve a file from the server you will have to modify your server.js to something like this:

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

http.createServer(function(request, response) {
    if(request.url=='/'){
        fs.readFile('./index.html', function (err, html) {
             if (err) {
                  res.send(500,{error: err});
             }
             response.writeHeader(200, {"Content-Type": "text/html"});
             response.write(html);
             response.end();
        });
    } else if(request.url=='/start.js'){
        fs.readFile('./start.js', function (err, jsFile) {
             if (err) {
                  res.send(500,{error: err});
             }
             response.writeHeader(200, {"Content-Type": "text/javascript"});
             response.write(jsFile);
             response.end();
        });
    }

}).listen(8080);

Hope this helps :)

Including JavaScript In Your Page, How do I run an HTML file with node js? I am learning how to use Node.js but I'm stuck. I am unable to load css and js files in my project. I am loading Bootstrap and Fontawesome from a CDN and they're rendering fine. As for my own custom css and js, they are not loading at all. My folder file path: folder index.html app.js package.json css main.css files file.pdf. app.js:

I think it's not able to find the js, Before you reference the js, ensure it is on the server and you can load it from the server, like this: 'http://127.0.0.1:8000/start.js'. All of our static files, such as img, css, js should be put on server, only then it will be referrenced.

Why is JavaScript not working with my HTML?, html', null, function(error, data) { if (error) { response.writeHead(404); response.​write('File  The message stated the HTML file was disk cached and the js file was memory cached. The HTML file was refreshed when I clicked the browser's refresh button, but the js file was not getting refreshed and was still showing empty in the "sources" tab from the initial running of the page before js content was added.

Can't get css files to load or javaScript to work in Node.js server , Serve HTML pages, scripts and styles using Node.js. the file has failed. Let's handle the error and respond with 404 status if the file is not found: The CSS file will load and the styles will be applied on the page. Similarly  We will be reading the html file using File IO, for that we need to load fs module. 2. Create an http server with the callback for request processing. 3. If the URL contains ‘/create’ value in it, the MyPage.html file will be read. If the file is not read successfully, the response with Http Status as Not Found will be sent for the request

Node.js Serving HTML pages and Static content, Read HTML file in Node.js using simple File IO operations and send a We will be reading the html file using File IO, for that we need to load fs module. If the file is not read successfully, the response with Http Status as Not  The basic concept is just raw file reading and dumping the contents. Still open to cleaner options, though! improve this answer. edited Aug 13 '14 at 0:48. 28 silver badges. 42 bronze badges. answered Jan 18 '11 at 5:26. 18 silver badges. 25 bronze badges. you should use fs.readFileSync in your case, it would be bad for the page to come up as

Using Node.js to read HTML file and send HTML response , Let's see how to create a server and render some HTML in Node.js. The Nginx or Apache process then serves the HTML files to the user. So in this function, we are not really going to do anything with the request, but we do need to set Now, we can load up http://localhost:8000/ in the browser and see what happens. Now it is rending the html file ; but is not rendering the CSS file or the JavaScript. What would I need to do to render the CSS file. Below is my html code.

Comments
  • I tried those alternatives and the path is properly referenced, however the file is not loading since console.log() doesn't make any logs. I believe the issue is related to what @BharathRao mentioned i.e. "file is not on the server"
  • Yes, that must the issue then. I edited my post with another method you could try.
  • I tried your solution with express following instructions on expressjs.com/en/starter/static-files.html i.e. putting start.js in a /public folder and it worked! Thank you.
  • Glad you got it working! express is usually my go-to as well ;)
  • I tried this, and the page is now endlessly loading. I suspect this is due to the fact the server cannot find /start.js. I am going to investigate a bit further.
  • @Wronski try debugging to find what is the url you get while doing a fetch for start.js, I might have missed something. Feel free to suggest an edit if you get it.
  • your code was correct. I had another .js file that was causing the endless loading. Once I removed reference to that file, the code loaded showing: This is a static paragraph. This text is loaded from a js file.
  • I suspect the file is not "on the server" because when I load localhost:8080/start.js I get the following error start.js:1 Uncaught SyntaxError: Unexpected token in the chrome console. How do I add a file to the server?
  • If start.js is throwing an error at line 1 then it is on the server, you just have a syntax error at line 1. What is your line 1 of that file? Double and triple check it for possible errors.