wetlip
wetlip

Reputation: 133

execute javascript file in dynamically created html page with nodejs webserver

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!') }; 

Upvotes: 1

Views: 3659

Answers (2)

wetlip
wetlip

Reputation: 133

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);

Upvotes: 1

Ferdi265
Ferdi265

Reputation: 2969

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

Upvotes: 1

Related Questions