dreamsys software

JavaScript Shell Scripting Tutorial

Shell Integration

One of the most useful packages for unix shell scripters in JavaScript is the Node child_process module. The simplest use of this module is to use the spawn function to spawn a shell command:

#!/usr/bin/env node

var cp = require('child_process');
var ls = cp.spawn('ls', ['-lsa']);

ls.stdout.on('data', function(data) {
	console.log('Message: ' + data);

ls.on('close', function(code, signal) {
	console.log('ls finished...');

This script will call the unix command "ls -lsa" and print the output to the console. The stdout.on('data') function will be called whenever data is flushed to stdout for the process being spawned.

This is useful, but often times when you spawn a process you want to actually process each line of the output individually, not the whole output in chunks. To do so, we can use the readline node module.

#!/usr/bin/env node

var readline = require('readline');
var cp = require('child_process');
var tail = cp.spawn('tail', ['-500', 'mylogfile.log']);
var lineReader = readline.createInterface(tail.stdout, tail.stdin);

lineReader.on('line', function(line) {
	console.log('Line: ' + line);

tail.on('close', function(code, signal) {
	console.log('ls finished...');

This script will open the process on unix "tail -500 mylogfile.log", read the output of the command and print it to the console line by line.

The first thing the script does is create a variable "readline", this is the object returned by the node module readline. Then it will create an object for the spawned process "tail" and give its stdout and stdin objects to the createInterface method of the readline module object.

Finally the object returned is stored in a variable "lineReader", which we then create an on 'line' event and log each line in the event function handler.

I hope you have enjoyed this tutorial introduction to shell scripting with JavaScript and Node.js.

Prev (Enums) | Next (TOC)

Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6