Life In The Node

Ifeoluwa Arowosegbe
Ife’s Tales
Published in
5 min readFeb 25, 2017

--

Recently, duty required that I picked up Node.js and little did I know that I was in for quite an adventure. I had been writing PHP for a while before this and I was quite struck by how different both tools are.

Please note that this is not a Node.js tutorial.
I think it would suffice to say I experienced quite a culture shock moving from PHP to Node and, I thought it’d be cool to outline some of these differences so anyone who’s considering playing with Node won’t feel as overwhelmed as I was when they start.

Serving…

Undoubtedly, the first element of surprise is the fact that you don’t need a traditional web server (Apache, Nginx etc.) to get your app up and running. You basically ‘create’ your own server within your app… to serve your app.

yeah, somewhat confusing.

With PHP you’d probably install WAMP or any of the other ‘AMPs based on your platform of choice and on some occasions run the default PHP server with php -S localhost:{port} so it was quite shocking to realize that I didn’t need any of these with Node.

Instead, to serve your Node app all you need to do is utilize Node’s core http module to help with your request and response handling. The following code snippet would create a basic http server in Node.js.

var http = require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write("Hello World!");
response.end();
});

server.listen(3333);
console.log("App is running at http://127.0.0.1:3333");

This creates a really simple Node.js server that immediately starts handling requests and returning responses… That’s some pretty cool stuff if you ask me.

Asynchronous Ops…

Traditionally, PHP statements are executed in the order which they appear i.e the chain of execution cannot get to the next statement if the current one hasn’t been executed.

This occurs in Node as well but the difference is you have the luxury of performing async operations and I must say that it really is amazing.

Basically, what this means is statements aren’t necessarily executed in the order which they’re written. This code snippet shows this behavior;

//synchronous operation. Outputs 1 2 3
console.log(1);
console.log(2);
console.log(3);
//asynchronous operation. Outputs 1 3 2
const fs = require('fs');
console.log(1);
fs.readFile('./main.js', (err, data) => {
console.log(2);
if (err) throw err;
});
console.log(3);

readFile is an async function that reads a file from the file-system. This kind of operation can be really expensive and we wouldn’t want it to block the execution of other parts of our program.

So, while the file is still being read, the next statement console.log(3); is executed before console.log(2); which is only executed when Node has finished reading the file.

I know this might seem confusing but I promise it gets better when you actually start writing.

Finally on async it is important to note that asynchronous functions do not immediately return their result. This might feel weird to devs that are used to performing database operations and capturing the result in a variable. This is not possible with Node if async calls are made to query the database and this leads us to our next outline.

Callbacks

Well, callbacks have actually been around in PHP for quite a long time but they aren’t as popular and widely used as JavaScript callbacks so it’s possible that you haven’t come across it and the whole concept might be a bit vague.

A callback is a function that is called when a particular operation has been completed.

Callbacks are passed to functions as arguments and the common convention is to pass the callback as the last argument of the function from which it would be called.

We’ll write a little program that logs the current top 4 teams in the NPFL just to show how easy it is to work with callbacks.

//declare an array of the top 4 Nigerian Premier League Teams
let npflTable = ['Plateau United', 'MFM FC', 'El-Kanemi', 'ABS'];
// prepend the team's position to their name
function prepend(callback){
npflTable.forEach((value, key) =>{
callback(value, key);
})
}
// actual funcion that prepares and logs the inforation
function logData(team, position){
console.log(position+1 + '. ' + team);
}
prepend(logData); //run the function

Let me explain what’s happening in the code above. We declare our prepend function by passing it a callback as an argument, we iterate over the npflTable array that we created and send the data to our callback function for logging.

The callback in the prepend function declaration is a place holder for the function that should be called when the function is run so, we created the actuallogData function that would be passed as the callback when we call ourprepend function.

You might ask, why not just log the data in the forEach loop? Doing that is fine, this is just to show us how callbacks can be implemented even in the simplest of scenarios.

NPM Is King

NPM is the official package manager for Node.js. In fact, Node’s world revolves round NPM. Yes, NPM is that awesome.

The PHP ecosystem has Composer for dependency management as well but PHP isn’t as dependent on Composer as Node is on NPM. It’s possible to build PHP apps without using Composer but it is extremely rare and even unlikely to build robust Node apps without NPM, it’s that serious.

So, if you plan to do anything useful with Node you have to become buddies with NPM. There is simply no other way.

There are several other Node.js discoveries that might seem daunting to beginners but the ones listed here are those you’ll immediately encounter when you start your journey in the Node.

As always, the key to getting better at anything is constant practice and dedication. With every line of code we get better than we were yesterday.

See you in the node.

Thanks for reading.
Kindly like and share this post if you find it useful.

--

--