1

i want to execute the javascript file in the header of an dynamically created html page with a node.js webserver. can't figure out how but must be possible.

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

function processRequest(request, response) {
  "use strict";

  var pathname = url.parse(request.url).pathname;
  console.log('Requested ' + pathname);

  response.writeHead(1000, { 'Content-Type': 'text/html' });
  response.write('<!DOCTYPE html><html ><head>');
  response.write('<meta charset="utf-8">');
  response.write('<title>' + 'Yay Node!' + '</title>');
  response.write('<link rel=stylesheet href=../styles/styles.css rel=stylesheet />');
  response.write('<script src=script.js type=text/javascript></script>');
  response.write('</head><body>');

  response.write('<h1><tt>' + 'jan' + '</tt></h1>');
  response.write('<script type="text/javascript">test()</script>')
  //response.write('<script type="text/javascript">script.onload = function () {    alert("from html Node!")}; </script>')
   response.write('<input id="clickMe" type="button" value="clickme" onclick="test()" />')
  response.write('</body></html>');
  response.end();
};

http.createServer(processRequest).listen(8888);

script.js:

document.onload = function () { alert('load Node!'); };
test = function() { alert('test Node!') }; 
3
  • "" marks are missing from script tags in src attribute Commented Jul 24, 2014 at 18:06
  • Also, what happens when you type http://localhost:8888 on your browser? Commented Jul 24, 2014 at 18:07
  • i see jan on a well formed page but the script.js is if it isnt is there. it is not executed nor the function test() is recognized Commented Jul 24, 2014 at 20:20

2 Answers 2

1

the problem is, that your browser can't find script.js

When it tries to get http://localhost:8888/script.js node answers with an html file that is the same as http://localhost:8888/.

In order for node to correctly serve the script file, you need to check the path and send the correct file.

add something like this to your processRequest function

if (pathname === '/script.js') {
    //code to send script
} else {
    //code to send html
}

you would have to do the same for the styles.css file as well

if you don't want to hardcode every file in your page, I would recommend using the npm module express

var express = require('express'),
    app = express(),
    server = require('http').createServer(app);

app.use('/', express.static(__dirname + '/static');

server.listen(8888);

this code will automatically send the files in /static when the browser requests them. if you want to create a dynamic page, you can add this between the app.use and the server.listen

app.all('/somedynamicurl', function (request, response) {
    //Dynamic page
});

now, if someone goes to http://localhost:8888/somedynamicurl they'll get this dynamic page.

I'd also recommend reading the express guide and the express docs

Sign up to request clarification or add additional context in comments.

Comments

1

this works. thanks to Ferdi265.

        // http://www.cburch.com/cs/340/reading/nodejs/

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

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

 var mimeTypes = {
'.js': 'text/javascript',
'.html': 'text/html',
'.css': 'text/css'
};

 function processRequest(request, response) {
"use strict";

var pathname = url.parse(request.url).pathname;
console.log('Requested ' + pathname);

var lookup = path.basename(decodeURI(request.url)), //|| 'index.html',
    f = lookup;


 fs.exists(f, function (exists) {
    if (exists) {
        fs.readFile(f, function (err, data) {
            if (err) {
                response.writeHead(500);
                response.end('Server Error!'); return;
            }
            var headers = {
                'Content-type': mimeTypes[path.
            extname(lookup)]
            };
            response.writeHead(200, headers);
            response.end(data);
        });
     // return;
    }

    else {

        response.writeHead(1000, { 'Content-Type': 'text/html' });
        response.write('<!DOCTYPE html><html ><head>');
        response.write('<meta charset="utf-8">');
        response.write('<title>' + 'Yay Node!' + '</title>');
        response.write('<link rel=stylesheet href=../styles/styles.css rel=stylesheet                />');
        response.write('<script src=script.js type=text/javascript></script>');
        response.write('</head><body>');

        response.write('<h1><tt>' + 'jan' + '</tt></h1>');
        response.write('<script type="text/javascript">test()</script>')
        //response.write('<script type="text/javascript">script.onload = function () { 
                                         alert("from html Node!")}; </script>')
         response.write('<input id="clickMe" type="button" value="clickme"   
     onclick="test()" />')
        response.write('</body></html>');
        response.end();

    }
    });
  };

   http.createServer(processRequest).listen(8888);

Comments

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.