What the Heck is Node.js?
By: Brad
Hi Brad,
I started looking into doing web development and have been hearing about Node.js; what the heck is that?
Good question, as the name implies Node.js, or just Node for short, is JavaScript; Node is a cross-platform runtime environment and library used to run applications written in JavaScript outside of a web browser. Node is used mostly for running real-time server applications; in simple terms its server side JavaScript.
Node.js was created in 2009 and lives as a very active open source project.
Why use Node.js?
Node is written using JavaScript so its quick to develop in as there is no compilation step, it has a large community with lots of existing packages and plugins so you don’t have to continually re-invent the wheel, it uses non-blocking I/O and asynchronous events, and a Node application is loaded into memory with no just-in-time parsing of the script code so its highly performant. Lastly your applications web based frontend is likely written in JavaScript using frameworks such as jQuery or Angular.js, by using Node.js both your frontend and backend will be written in JavaScript allowing more shared code.
Node.js is an event driven technology, there is a single event loop which runs automatically when the Node.js process is started. As events, such as HTTP requests, or keyboard input come in the different modules within Node.js which you instantiate when you start your application will invoke callbacks that you provide to handle said events. Once all the callbacks are processed the event loop will wait for another event.
Event Loop and Blocking I/O
Its worth noting here that the Event Loop in Node.js is single threaded, so if any of your callbacks executes the sleep() method it will halt the entire application; the Event Loop will stop processing events causing events to queue up until the sleep method returns control to the main thread.
There are other blocking methods other than sleep() such as reading a file.
var fs = require('fs'); var contents = fs.readFileSync('package.json').toString(); console.log( contents );
File I/O are blocking calls, in the above when we call readFileSync()
the Node.js Event Loop will be blocked from processing other events while the main, and only thread, is busy reading the package.json file. New events which come in during the read will be queued up and processed once the read operation has completed.
Because blocking the Event Loop is non-optimal since it will lock up your application and render poor performance and user experience its better to design your code to use asynchronous APIs. This is inline with Event Driven Programming in general, events come in kicking off specific actions, those actions are initiated but we do not wait for the action to finish to return control back to the Event Loop. Its like getting a phone call and the caller asks you to do something. If the something you need to do will take a while generally you tell the caller sure I’m on it, I’ll call you back when its done then hang up allowing them to move on to some other task while you work in the back ground.
As it happens Node.js has synchronous and asynchronous APIs so you can use the right kind of control flow for your application. Below as an example here is how you can read a file without blocking the Event Loop.
var fs = require('fs'); fs.readFile('package.json', function( error, buffer ) { console.log( buffer.toString() ); });
In the above instead of waiting for the file to be read and print the returned value to the console we tell the File System module to read the file and tell it when its done execute this callback. That is we called the File System and asked them to read the file, they said sure we’ll call you once we’ve finished reading the file.
Node Package Manager (NPM)
Node.js has a thriving community of developers who have been creating libraries for all sorts of functionality. Its likely that if your application needs to interface with a public API or support a common feature such as e-mail support there will already be a library you can import saving you the trouble of developing it your self.
The nice thing about Node.js is that these libraries, or packages, are all managed and easily obtainable via the Node Package Manager (NPM). This is a service not unlike Ruby gems or .Net’s NuGet. There is a website you can go to called npmjs.com that you can use to search for different packages that you might need. Just like Ruby gems or NuGet, Node.js comes with tools that allow you to easily download and install the packages either globally on your system or on a project per project bases.
The NPM tools are installed into your environment automatically when you install Node.js. To use it to install a package you simply have to type the following from a command prompt: > npm install package_name
The above will install the package local to the project your terminal is currently in. You can also install packages globally independent of any project; you would do this for packages which provide you things like code generators or debugging tools which you would use during development but would not be required by your application to function. NPM can also be setup to record a list of dependencies in a configuration file so that you do not need to check in the dependent packages into your source repository. When you clone a repository you can tell NPM to read the configuration file and install any missing packages with the following command: > npm install
Notice that you do not specify a package name; if no package name is provided NPM will look for a package.json configuration file in the current directory and if it finds one will install any missing dependencies listed in the file.
I’ll talk more in-depth about NPM in a future post, but if you have ever used Ruby gems or NuGet then you’ve pretty much got the idea behind NPM.
Commercial break...
Node.js Example
Here is a simple example of a Node.js application.
Lets create a new JavaScript file called app.js and populate it with the following code:
console.log("Hello World");
Now in a terminal type the following: > node app.js
What you’ll get now in your terminal is the text Hello World. That’s it you’ve executed a Node.js application; that is you ran JavaScript code outside the browser as a stand alone application.
Serving Node.js
A more common use for Node.js is to host a web service, either a web application or an API. To do this we can do basically the same as we did above however this time will use the HTTP module which comes built into Node.js.
Lets create a new file called server.js and fill it in with the following code:
var http = require('http'); // Import Module // Create a server which response to any request with a 200 and simple text. var server = http.createServer( function( request, response ) { response.writeHead(200, { "Content-Type": "text/plan" } ); response.end("Hello World\n"); }); server.listen(3000); // Listen for requests on port 3000
Now in a terminal type the following: > node server.js
Notice this time that the terminal does not terminate. It is busy running the Node process which is off running an event loop. What is happening here is that our Node.js code is running within an event loop listening on port 3000 for incoming requests. Once a request comes in our application will respond by printing out the string Hello World. The way this works is that when the server created by the HTTP module registers an incoming request it will execute the callback function we provided it via the createServer()
builder method. Our specific callback method above will respond to any request with the return code 200 (OK) and the text Hello World.
To see this in action open a web browser and navigate to http://localhost:3000. You will see the text Hello World show up.
So in short that is what the heck Node.js is; a framework for running JavaScript outside of the browser which is commonly used to respond to HTTP requests in the form of web applications or RESTful APIs.
I hope that helps, if you have any questions feel free to leave them below and I’ll try to answer them as time permits. I plan on doing up tutorials on how to develop APIs and web applications using Node.js so stay tuned for future posts and feel free to leave suggestions for future tutorials.
Until next time think imaginatively and design creatively