ben_aaron ben_aaron - 1 year ago 71
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:



<!DOCTYPE html>
<meta charset="UTF-8">
<script src=""></script>
<p id="p1">

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

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

My node script should serve the
and run the function from

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


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'

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 Source

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

        ...  // 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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download