Using Node.js for Server-side Programming in JavaScript

[Echo Server] [Server using socket.io] [Pi server that returns command responses]
[Server that logs requests] [Links to other servers]

This page is to encourage you to extend your JavaScript skills to server-side programs. Our demonstration code is based on the useful pages linked to in this paragraph. The Project Spot provides a good introduction to the use of Node.js followed by a clear explanation of the need for callbacks. For a Node.js website, use a node static server. The fs Node.js module enables access to the file system on the server. This tutorialspoint page gives detailed examples.

Echo Server

This is the equivalent of our Smart Pascal echo server for a Raspberry Pi running an Apache web server. You can test it with EchoClient.html (the output from our Smart Pascal client program described on the same page).

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

http.createServer(function (request, response) {
  request.on('data', function (msg) {
    response.write(msg);
    fs.writeFile('trial.txt', msg, null);
    console.log('Echoed and saved: ' + msg); 
  });
  
  request.on('end', function() {
    response.end();
    console.log('End of response');
  });
}).listen(8080);

console.log('Server running at http://192.168.0.6:8080');

Server using Socket.io for Real-time Updating of Clients

This is the equivalent of our Smart Pascal server. You can test it with ButtonSizeClient.html (the output from our Smart Pascal client program) in the public folder.

var static = require( 'node-static' ),
  port = 8079,
  http = require( 'http' ),
  value = 0,
  connectionNum = 0;    

var webserver = new static.Server('./public',{
  cache: 3600,
  gzip: true
});

var server = http.createServer(function(request, response){
  request.addListener('end', function(){
    console.log('http request: ' + request.url);
    if (request.url == '/') 
      request.url = '/ButtonSizeClient.html';
    webserver.serve(request, response);
  }).resume();
});

var io = require('socket.io').listen(server);
io.sockets.on('connection',    // waiting for connections
  function(socket){
    connectionNum += 1;
    socket.emit('dataConnection', connectionNum.toString());  // pushes connection num to client upon connection
    socket.on('requestFromClient',  // waiting for a special request from the client
      function(data, callback){
        console.log('Received from client: ' + data);
        value = parseInt(data, 10);
        if (value > 500)
          value = 80;
        io.sockets.emit('dataFromServer', value.toString());  //send to all clients
      });
  });
server.listen(port);
console.log('Server running at http://192.168.0.6:8079');

Pi Server that Returns Command Responses to Client

This is a JavaScript version of our server that we trialled on a Raspberry Pi. You can test it with the output HTML file of the Smart Pascal client described on the same page.

var static = require( 'node-static' ),
  port = 8079,
  http = require( 'http' ),
  value = 0;   

var webserver = new static.Server('./public',{
  cache: 3600,
  gzip: true
});

var server = http.createServer(function(request, response){
  request.addListener('end', function(){
    console.log('http request: ' + request.url);
    if (request.url == '/') 
      request.url = '/PiClientExec.html';
    webserver.serve(request, response);
  }).resume();
});

var io = require('socket.io').listen(server);
io.sockets.on('connection',    // waiting for connections
  function(socket){    
    socket.on('requestFromClient',  // waiting for a special request from the client
      function(data, callback){
        console.log('Received from client: ' + data);
        var exec = require('child_process').exec;
        exec(data, function(err, stdout, stderr){
          if (err){
            callback('error code ' + err.code);
            return;
          }
          callback(stdout);
        });
      });
  });
server.listen(port);
console.log('Server running at http://192.168.0.6:8079');

Server that Logs Command Requests

This is a JavaScript version of our server that we trialled on Windows 10. You can test it with the output HTML file of the Smart Pascal client described on the same page.

var static = require('node-static'),
  port = 8079,
  http = require('http'),
  fs = require('fs'),
  value = 0;

var ws = fs.createWriteStream('requests.txt', null);  

var webserver = new static.Server('./public',{
  cache: 3600,
  gzip: true
});

var server = http.createServer(function(request, response){
  request.addListener('end', function(){
    console.log('http request: ' + request.url);
    if (request.url == '/') 
      request.url = '/WinClientExec.html';
    webserver.serve(request, response);
  }).resume();
});

var io = require('socket.io').listen(server);
io.sockets.on('connection',    // waiting for connections
  function(socket){    
    socket.on('requestFromClient',  // waiting for a special request from the client
      function(data, callback){
        console.log('Received from client: ' + data);
        ws.write(data + '\r\n', 'utf8');
        var exec = require('child_process').exec;
        exec(data, function(err, stdout, stderr){
          if (err){
            callback('error code ' + err.code);
            return;
          }
          callback(stdout);
        });
      });
  });
server.listen(port);
console.log('Server running at http://192.168.0.2:8079');

Programming - a skill for life!

How to apply your knowledge of Pascal when learning JavaScript