Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

execute a Nodejs script from an html page?

execute a Nodejs script from an html page?


I am currently using Express.js to create my website. My main server Script is called I also created a script called request.js that makes a GET request and displays the response with


I have no problems when running the script from the console: node request.js

My question is: How do I make the "Get this list" button on my the page respond to a click by displaying the list on the same page (that is, executing request.js on the server and showing the result)?


 * Module dependencies.

var express = require('express')
  , routes = require('./routes');

var app = module.exports = express.createServer();

// Configuration

  app.set('views', __dirname + '/views');
  app.set ('view engine', 'coffee');
app.register('.coffee', require('coffeekup');

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

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

app.configure('production', function(){

app.get('/', function(req, res) {
  res.render('index',{ layout: false });

console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

doctype 5
html ->

  head ->

p -> "hey"

Problem courtesy of: Louis


I use plain JS and not coffee script, so here's an example per Fosco's comment (call it server.js):

var express = require('express'),
    list = require('./request.js').Request; // see  template

var app = express.createServer();

app.use(express.static(__dirname + '/public')); // exposes index.html, per below

app.get('/request', function(req, res){
    // run your request.js script
    // when index.html makes the ajax call to, this runs
    // you can also require your request.js as a module (above) and call on that:
    res.send(list.getList()); // try res.json() if getList() returns an object or array


Write your index.html file, and save it in the /public subfolder of your node app directory (which is exposed above, via express.static).:

Get this List

If you're including your request.js as a module, it could be as follows:

var RequestClass = function() {
    // run code here, or...

// ...add a method, which we do in this example:
RequestClass.prototype.getList = function() {
    return "My List";

// now expose with module.exports:
exports.Request = RequestClass;

Run node server.js on your server. Then head over to

Solution courtesy of: Wes Johnson


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

execute a Nodejs script from an html page?


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription