This is the second post in the series, “Node for X Developers”, which includes Node for Java Developers.

PHP is ubiquitous. It powers most of the web thanks to widely popular content management systems (CMS) applications like WordPress, Joomla!, and Drupal which were built on PHP. I myself entered the world of web development by learning PHP and building persistent web apps with it and MySQL.

Nowadays, if you are working in web development, most likely you are developing in browser JavaScript a lot. More and more logic is being moved to the browser (so called thick client architecture) to boost User Experience and performance. This is where Node, which is a JavaScript run-time on the server, becomes very beneficial.

Disclaimer: PHP started as a templating language so it’s not fair to compare PHP and Node, but guess what? Life is unfair so get used to it. Most people would use either PHP or Node, not both. It’s a very common question to decide between PHP vs Node because in the end, they both achieve the same goal — to have a working web app. Read my old but still highly visited article on PHP vs Node at webapplog.com.

In this short guide, I’ll help PHP developers to start transitioning into Node to be able to build with JavaScript across the entire tech stack (a.k.a. full stack JavaScrip). We will go through the following topics:

  • Terminology
  • Architecture
  • Language
  • Further study

Let’s jump right into the tech terms because they are the foundation without which we won’t be able to understand each other.

Node Terminology for PHP Developers

I didn’t do any studies and don’t have any hard data but these are the most used terms by Node developers based on my personal observation:

  • Node core modules: Modules which are bundled into the Node platform itself. Node comes with a lot of core modules so developers can build almost any networking app (client and server).
  • npm: Node package manager; think composer in PHP
  • npmjs.org: npm’s online package repository; think packagist.org for PHP
  • package.json: meta data for your project; think composer.json for PHP’s composer
  • node_modules: Where npm packages live when you install them in your project.
  • Handlebars, Mustache, Jade, Pug: template engine libraries. In PHP you would just write in .php, but in Node you need a separate library because .js Node files do not automatically translate into HTML
  • Node Foundation: open source organization which handles legal, licensing, and marketing for Node.js
  • ECMAScript and TC39: organization and committee that decide on the future of JavaScript language standard which in turn gets added to Node later.
  • ES6/ES2015, ES7, ES8 or ES.Next : New JavaScript (and in turn Node) language standards of mostly sugarcoating features (very true for ES7 and somewhat true for ES6 and ES8).
  • V8: Google Chrome’s V8 engine for JavaScript which used to power Node. There’s also a way to make Node work with Microsoft’s EDGE Chakra engine.
  • LTS: Long-term support. Currently Node 6 is LTS while Node 7 is not. In PHP, there’s only one current version which is coincidentally also 7.
  • Promises, async/await, generators: Patterns (mostly from front-end JS) to write asynchronous code
  • Express: The most popular (de facto standard) framework for Node; think CakePHP.
  • Non blocking I/O: System design pattern which allows you to create systems that can handle multiple input and output operations by delegating them and utilizing the waiting time to handle other I/O operations. PHP analogies: ReactPHP and amphp.
  • Event loop: A part of V8 and the thing which powers non-blocking I/O.
  • Static server or files: Regular HTTP(S) web server like Express static, node-static or http-server to handle files which don’t have any template instructions in them. Think Apache httpd when it serves HTML files without PHP code in them.

These terms should be enough for you to proceed, be comfortable reading Node docs and maybe even pass as a Node developer at a conference (at lease for a five-minute small talk).

Architecture: Most Common Confusions When Moving from PHP to Node

When it comes to architecting PHP and Node apps there are similarities and differences.

In PHP, you have to use an HTTP web server like Apache httpd. PHP will be a module there and Apache httpd will handle the incoming traffic. When httpd sees a certain rule defined in its .htaccess, it’ll redirect that traffic to your .php files which will be processed (interpreted) on the fly by the PHP module. In comes the HTTP request, out goes HTML. At the minimum, PHP files are HTML with PHP commands in them (template engine).

Node on the other hand, doesn’t need Apache httpd. Node is a platform in which you can build both your web server and your app. Also, Node was built with networking in mind so it comes with non-blocking I/O architecture, package manager and core modules (which are enough by themselves to build almost any networking app). PHP has non-blocking I/O frameworks but they are not part of the PHP environment by default. And as we know, each framework has its own cost in terms of learning, customizing its behavior and maintaining it.

Because of that, Node set up is much simpler and requires fewer moving parts and fewer dependencies on other technologies. This in turn saves time on maintenance especially in the long term.

But sometimes developers don’t even need a web server (continuos running process). Maybe they just need a simple one-time-run script. Node can be used to write scripts for deployment, data processing, or to create a networking client (an IRC chat?). Developers just run Node scripts from command line or bash scripts. It’s possible to run PHP scripts from command line too.

Speaking of cloud, you can put Node scripts into cloud with services like AWS Lambda, IBM Bluemix or Microsoft Azur Functions to make them cost-effective, easy-to-maintain pieces of logic which are triggered by timers, HTTP requests or other events. With time, Function as a Service Provider will add other languages like PHP (if they haven’t supported them yet — most do). When using cloud (FaaS or PaaS), configuration of Apache httpd and PHP is taken cared of for you so the setup is not so complex compared to Node.

As for the use cases, I see a lot companies (especially small non-tech ones) using off-the-shelf PHP apps for e-commerce or content management like Magento or Drupal, but I can see a team or a company which would choose PHP for a new REST API or a micro-service. I only saw PHP in projects or teams where you already have legacy PHP code and well-honed PHP skills (e.g., Facebook). Most often the weapon of choice for new REST APIs is Node, Go, Java or Scala, not PHP.

In other words, PHP is often used to power traditional (think server) web apps where you render HTML on the server (mostly for SEO purposes). Think WordPress! Conversely, Node is often used to build REST APIs which power front-end (thick client) apps. Of course, it’s totally possible to build REST APIs in PHP, and traditional web apps in Node but that is not a common use case. (For Node, you will need to bring a template engine to perform server-side rendering).

To summarize, Node offers simplicity and faster I/O-bound systems and JavaScript environment, over PHP. And speaking of the JS environment, let’s take a look at how two languages compare.

PHP and Node Main Language Syntax Differences

Both PHP and Node are interpreted, so developers can use a simple code editor to write code. There’s no need for an IDE since there’s no compilation for either of them. This allows developers to prototype faster. They can save a file, hit “refresh” and see the results. No need to wait for the compiler to finish its work.

Hello World PHP vs Node

A typical PHP file is just an HTML file with PHP instructions which start with <?php and end with ?>. Each statement is written on a new line and ends with a semi-colon. In Node (and JavaScript), semi-colons are optional as long as you write statements on a new line. Also, the entire Node file is a script. There’s no HTML. HTML only comes to play when you write a server response.

<?php
echo "Hello World";
?>

In Node, it will be either for a simple print in the terminal window (command prompt):

console.log('Hello World')

or a small Node server (with the core http module) for the HTTP response:

const http = require('http')
http.createServer((req, res)=>{res.end('Hello World')}).listen(3000)

PHP and Node Modules, require and Friends

You might have noticed require on my last snippet. It imports logic (a class, object or a function) from external module. In PHP, there’s a similar command require (docs), but the difference is that a PHP’s import dumps everything into the scope. For example, this is a module.php file which has the logic we want to re-use in other files:

<?php

$origin = 'PHP';
$destination = 'Node';

?>

And this is a main.php in which we use module.php:

<?php

echo "From $origin to $destination"; // From PHP to Node

require 'module.php';

echo "From $origin to $destination"; // From PHP to Node

?>

In Node, the module mechanism will act in a safer manner by exporting data or functions only into a variable (unless you omit var, in which case a variable becomes global and available everywhere, but this is an anti-pattern and should be avoided.) For example, module.js:

module.exports = {
  origin: 'PHP',
  destination: 'Node'
}

And in main.js, we use string templates and strings from the module file:

var origin, destination
console.log(`From ${origin} to ${destination}`)  // From undefined to undefined

require('./module.js')
console.log(`From ${origin} to ${destination}`)  // From undefined to undefined

var {origin, destination} = require('./module.js')
console.log(`From ${origin} to ${destination}`)  // From PHP to Node

There are also require_once and include in PHP. In Node, there’s only one require and it’s cached, hence no need for another function to require_once. Also, Node’s require is synchronous and will stop the execution if the dependency is not there which is similar to PHP’s require but not PHP’s include (produces only a warning).

If you are familiar with namespacing in PHP (most developers might not be since it was only added in PHP 5 and up), Node modules serve the same purpose—avoid conflicts of names from different sources.

Community Modules in PHP and Node

One last bit of a very important information when it comes to modules coming to Node from PHP- when it comes to modules which are simply files of Node or PHP, developers just put them in the project folder. Both languages are interpreted so the code of the modules are just plain text. In this case, both Node and PHP are similar: create a file, save it in the same folder or a subfolder and use them with require. However, there’s an important distinction when it comes to bigger modules downloaded from the community, especially the modules which require some native code like C/C++.

When Node developers use npm modules, i.e., modules from an open source community (a.k.a. userland), they put them into the local folder node_modules inside of the project folder. Well, actually npm CLI puts it there when npm i mongodb is executed.
And there’s also a global installation (npm i -g gulp), but it’s almost never used and should be avoided for the most part, like a cold beer during sore throat flu, due to possible conflicts of versions.

In Node, the structure will be similar to this in which node_modules has an npm package qs while utilites has project files acting as modules.

/api
  /node_modules
    /qs
  /utilites
    hash.js
    left-pad.js
  index.js
  package.json

Conversely, in PHP you would install modules on the server (e.g., Apache httpd or some global folder on local developer machine). For example mongo or curl. That’s the difference.

Making HTTP Requests in PHP and Node

The next very important functionality which is used almost in all web apps — making HTTP requests to another service. In PHP, I know of at least three ways to do it: cURL, PECL and file_get_contents. Let’s cover cURL (docs) since it’s more versatile. CURL method uses libcurl, a library created by Daniel Stenberg, which supports not just HTTP, but HTTPS, HTTP/2, and other popular protocols.

A very simplistic GET request example of PHP’s cURL will include initializing, setting of the options and making a call:

<?php

$ch = curl_init('http://azat.co');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);

?>

And the POST will need another option and the data:

<?php

$url = 'http://node.university/api';
$myvars = 'myvar1=' . $myvar1 . '&myvar2=' . $myvar2;

$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );
var_dump($response);

?>

In Node, there’s http module which is part of the core, meaning developers don’t need to download it from an npm—the module which is part of the Node platform. Here’s a GET request in Node 7:

const http = require('http')
http.get('http://azat.co', (response) => {
  let rawData = ''
  response.on('data', chunk => rawData += chunk)
  response.on('end', () => {
    console.log(rawData)
  })
})

Although it’s possible to use http for all types of requests, most Node developers prefer to use one of the npm packages because they will have a more compact syntax, do JSON parsing and support Promises/async await. One of such libraries is axios.

Performing a POST request with axios is straightforward if you are familiar with Promises. Even if you’re not familiar with Promises, you can guess that the callback to then is what happens in the end when we receive the response back:

const axios = require('axios')
axios.post('http://node.university/api/v1/students', {
    firstName: 'Azat',
    lastName: 'Mardan'
  })
  .then(function (response) {
    console.log(response)
  })
  .catch(function (error) {
    console.log(error)
  })

Note: Interestingly, there’s a new standard fetch API for JavaScript which supports promises and async await functions. Because there’s no XMLHttpRequest in Node (server environment), fetch is not in the core Node, but can be used from a module such as node-fetch

Further Node Study for PHP Developers

I was a PHP developer for many years. I luckily escaped any serious CGI development and PHP was my first serious web language after a short foray into then mostly-unknown-besides-the-academia Python. Fast forward a few years and my last project was done in PHP 5 and I was happy that it had classes. I might have even used a bit of namespacing but the / looked weird to me. The project I built was an MVC app to serve classified ads (a Craigslist clone). I later open sourced it as open list: https://github.com/azat-co/openlist.

Then I moved to Node because it made so much sense and, it might sound lame, but it’s fun. I never looked back and so hadn’t many other developers. Node is catching fire faster than the latest Hollywood block buster. Node started in small companies and startups, but it’s not for hipsters anymore. Node is used by IBM, Microsoft, Uber, Intel, PayPal and other giants. It’s capturing market share on both worlds: “self-taught” developers (from PHP) and “professional” developers (from Java). Are you going to join the Node movement which has already gone mainstream?

This is it for our quick PHP to Node guide for developers. We’ve covered the terminology and three of the most important use cases: modules, making HTTP requests and of course Hello World. This is just a beginning of your journey. To continue, take Node and MongoDB Foundation and read Full Stack JavaScript.