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’.
I think the code is really simple and pretty self explanatory, but lets 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 puts 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 change the file to be executable (if you are on linux, just use chmod 744 fileName) and launch it.