ben_aaron ben_aaron - 3 months ago 12
jQuery Question

Import local js function to node.js

I'm stuck on this for a while now and think this is because I misunderstand the linking of files in node.js.

I have the following structure:

./main_test.html
./js_test.js
./node_test.js


The
main_test.html
is:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<p id="p1">
</p>
</body>
</html>


The js_test includes a function to print text to the
<p>
tag with id
p1
and is this:

module.exports.print_to_p = function(){
$("#p1").text('This worked.');
};


My node script should serve the
main_test.html
and run the function from
js_test.js
:

var http = require('http'),
fs = require('fs'),
$ = require('jQuery'),
port = 1337,
dep1 = require('./js_test.js');

dep1.print_to_p();

var app = http.createServer(function(request, response) {
fs.readFile("main_test.html", function(error, data) {
if (error) console.log(error);
response.writeHead(200, {
'Content-Type': 'text/html'
});
response.write(data);
response.end();
});
}).listen(port);


It says
ReferenceError: $ is not defined
which I assumed was due to it not referencing JQuery but changing this to
document.getElementById('p1').innerHTML = 'This worked';
didn't solve this.

How can I run the Javascript/JQuery in my node app?

Answer

The problem is that your http-request cannot handle your linked files as they are all interpreted as html-files. If you let your server handle different file types using the same content-type the dependencies are not delivered correctly. You could either fix this using some libraries or packages like express or mime-type (which helps to individually identify content-types), or you could do it manually by identifying the content-types of your dependent files and adjusting your request.

An example to do this would be to modify your node_test.js as follows:

var http = require('http'),
fs = require('fs'),
port = 1337,
path = require('path');

var app = http.createServer(function (request, response) {
    var filePath = request.url;
    var extension = path.extname(filePath);
    var contentType = 'text/html';  // your default content-type

    switch (extension) {
        case '.js':
            contentType = 'text/javascript';
            break;

        ...  // here you can specify the content-types you need 
    }

    fs.readFile(filePath, function(error, data) {
        if (error) console.log(error);
        response.writeHead(200, {
            'Content-Type': contentType
        });
        response.write(data);
        response.end();
    });
}).listen(port);

Note that you also have to specify the file to be read here! The http-request is called for every dependent file independently which means that each file has to be handled and read. In order to get the correct file extensions you can use a node-package called path.

Comments