Node.JS demo program
Let's create some NODE.JS application that will communicate with active terminal and make it runnable from Linux bash shell...
Prerequisites
-
Install Node.JS
-
Create folder for your project and add file package.json
-
Open package.json with text editor and add minimum required, then save it
{}
-
Position to project folder from console and execute following to install required lib
npm install ws --save npm install mem-cache --save
Program
Create index.js in project folder and add code shown at the end of the page.
Code can be executed as bash shell script simply by calling ./index.js or with Node.JS itself by executing from command line with node index.js.
index.js file
#!/usr/bin/env node
const WebSocket = require('ws');
const Cache = require('mem-cache');
var cache = new Cache();
var ws = new WebSocket('ws://localhost:5250')
/**
* Store request into cache and make remote request
*/
function request(req, callback) {
// store request into cache for 30 seconds
cache.set(req.rid, {callback : callback}, 30000);
// send request to GreenScreens Native Terminal
ws.send(JSON.stringify(req));
}
/**
* Receive response from terminal and process data
*/
ws.on('message', function(resp, raw) {
// parse received text data into JSON
let data = JSON.parse(resp);
// take rid from response and look into cache
let cdata = cache.get(data.rid);
// if request stored into cache and have callback function, execute it
if (cdata && typeof cdata.callback === 'function') {
cdata.callback(data);
}
});
/**
* Signal when connection established
*/
ws.on('open', function open() {
// prepare A-HLL API command
let req = {"cmd": "echo", "rid": Date.now()};
// send A-HLL command to terminal and attach response handler
request(req, function(resp){
console.log(`Response arrived from terminal for request ID: ${resp.rid}`);
});
});