CodeProject
Introduction
I started learning Node.js. I consider this platform will be a widely used one and will have a great success in the near future. I know, many start-ups and larger companies have products based on Node.js but it is not as widespread between back-end technologies as .NET or Java is.
I thought, for fun, I will implement some of the most used Linux shell commands. I started with the yes command. The yes command repeatedly outputs a string
until the process is killed. If you pass a parameter to this command, it will repeat that parameter as string
or it will put out the letter 'y
'.
Here is the code of my node.js version of yes command:
#!/usr/bin/env node
var DEFAULT_TEXT = "y\n";
var CUSTOM_TEXT = "";
var printUsage = function() {
process.stdout.write("Usage: yes <optional_parameter>\n");
};
var writeDefaultText = function() {
process.stdout.write(DEFAULT_TEXT);
};
var writerCustomText = function() {
process.stdout.write(CUSTOM_TEXT);
};
process.on("SIGINT", function() {
clearInterval(writeDefaultText);
clearInterval(writerCustomText);
process.exit(0);
});
if(process.argv.length == 2) {
setInterval(writeDefaultText, 2);
}
else if(process.argv.length == 3) {
CUSTOM_TEXT = process.argv[2];
if(CUSTOM_TEXT[CUSTOM_TEXT.length - 1] != "\n") {
CUSTOM_TEXT += "\n";
}
setInterval(writerCustomText, 2);
}
else {
printUsage();
}
I think the code is really simple and pretty self explanatory, but let's look at the more trickier parts. The first line of the code notifies the shell, this file should be executed using the node command. Afterwards, two global variables are declared: DEFAULT_TEXT
and CUSTOM_TEXT
.
There are 3 functions declared, printUsage()
, writeDefaultText()
, writeCustomText()
. All of these put out some value to the process.stdout
stream.
I think the most important part of the code starts when there is an event handler attached to the process. This is done through the process.on("event", handlerFunction)
method, which is part of the Node.js framework. In the code we define, when the process received a SIGINT
signal, then the attached event handler function should be invoked. You can send/raise the SIGINT
signal to your process with the help of CTRL+C key combination.
Afterwards the two cases are treated, if there was no parameter passed to the process, it will start to put the 'y
' value and a new line, till the process receives the SIGINT
signal. If there was a parameter passed to the process, it will put that out and a newline character repeatedly. In case there is more than one parameter passed to the app, it will print out a helper text, which shows how to use this mini app.
To be able to start the app, you have to change the file to be executable (if you are on Linux, just use chmod 744 fileName
) and launch it.