Category: npm

  • Node.js for PHP Developers: A Beginner’s Guide

    Node.js for PHP Developers: A Beginner’s Guide

    Node.js for PHP Developers: A Beginner’s Guide

    If you are already comfortable building websites with PHP — whether vanilla PHP, WordPress, or Laravel — learning Node.js might feel like stepping into a parallel universe. The language looks different, the mental model is different, and things that were simple in PHP suddenly require a new way of thinking.

    But here is the good news: the concepts you already know transfer more than you think. In this guide, I will walk you through Node.js from the perspective of someone who already knows PHP, so you can start writing real Node.js code as fast as possible.

    1. What Is Node.js?

    Node.js is a JavaScript runtime — it lets you run JavaScript code outside of a browser, on your server or your local machine. It was built on top of Google Chrome’s V8 JavaScript engine, the same engine that runs JavaScript in your browser.

    In simple terms: just like PHP lets you write server-side code that generates HTML and talks to databases, Node.js lets you do all of that — but with JavaScript.

    PHP Developer’s Analogy: Think of Node.js as PHP, but instead of Apache or Nginx executing your scripts, Node.js is the server itself. It handles HTTP requests natively.

    2. PHP vs Node.js: Key Differences

    Before diving into code, let’s look at the most important differences side by side:

    Feature PHP Node.js
    Language PHP JavaScript
    Execution model Synchronous (by default) Asynchronous / event-driven
    Server Apache / Nginx runs PHP Node.js IS the server
    Package manager Composer npm / yarn / pnpm
    Popular framework Laravel, Symfony Express.js, Fastify, NestJS
    Database (common) MySQL / MariaDB MongoDB, PostgreSQL, MySQL
    Best for CMS, traditional web apps APIs, real-time apps, microservices

    3. Synchronous vs Asynchronous Code

    This is the biggest mental shift when moving from PHP to Node.js. PHP is mostly synchronous — each line runs one after the other, and the script waits for each operation to finish before moving to the next.

    PHP — Synchronous Example

    <?php
    // PHP waits for the file to be read before continuing
    $content = file_get_contents('data.txt');
    echo $content;
    echo "Done!";
    ?>

    Node.js — Asynchronous Example

    const fs = require('fs');
    
    // Node.js does NOT wait — it continues and calls the function when ready
    fs.readFile('data.txt', 'utf8', function(err, content) {
      if (err) throw err;
      console.log(content);
    });
    
    console.log("This runs BEFORE the file is done reading!");

    Key Point: In Node.js, operations like reading files, querying databases, or making API calls are non-blocking. Node.js keeps processing other requests while it waits for those to finish. This is what makes Node.js so fast for handling many simultaneous users.

    Modern Node.js: async/await (much cleaner)

    You don’t need to write callback functions everywhere. Modern Node.js uses async/await, which makes asynchronous code look almost synchronous:

    const fs = require('fs/promises');
    
    async function readMyFile() {
      const content = await fs.readFile('data.txt', 'utf8');
      console.log(content);
      console.log("Now this runs after the file is ready.");
    }
    
    readMyFile();

    4. Your First Node.js Server

    In PHP, Apache handles the HTTP layer. In Node.js, you create the server yourself using the built-in http module. Here is the simplest possible web server:

    // server.js
    const http = require('http');
    
    const server = http.createServer(function(request, response) {
      response.writeHead(200, { 'Content-Type': 'text/html' });
      response.end('<h1>Hello from Node.js!</h1>');
    });
    
    server.listen(3000, function() {
      console.log('Server running at http://localhost:3000');
    });

    Run it in your terminal:

    node server.js

    Open your browser at http://localhost:3000 and you will see your response. No Apache, no Nginx, no virtual host configuration needed.

    5. npm vs Composer

    As a PHP developer you already know Composer — it manages your PHP dependencies via composer.json. Node.js has the exact same concept: npm (Node Package Manager), with a package.json file.

    Action Composer (PHP) npm (Node.js)
    Initialize project composer init npm init
    Install a package composer require guzzlehttp/guzzle npm install axios
    Install all dependencies composer install npm install
    Config file composer.json package.json
    Lock file composer.lock package-lock.json
    Vendor folder /vendor /node_modules

    6. Building Routes with Express.js

    Writing raw http.createServer() gets tedious quickly. That is why Express.js exists — it is the Node.js equivalent of a micro-framework like Slim PHP or a simplified Laravel router.

    Install it:

    npm install express

    Build a simple API with multiple routes:

    // app.js
    const express = require('express');
    const app     = express();
    
    app.use(express.json());
    
    // GET route
    app.get('/', function(req, res) {
      res.send('Welcome to my Node.js API!');
    });
    
    // GET with URL parameter — like $_GET['id'] in PHP
    app.get('/users/:id', function(req, res) {
      const userId = req.params.id;
      res.json({ message: 'User found', id: userId });
    });
    
    // POST route — like handling a form submission
    app.post('/users', function(req, res) {
      const data = req.body;
      res.status(201).json({ message: 'User created', data: data });
    });
    
    app.listen(3000, function() {
      console.log('Express server running on port 3000');
    });

    PHP Comparison:
    req.params.id$_GET['id']
    req.bodyjson_decode(file_get_contents('php://input'), true)
    res.json({...})echo json_encode([...]); exit;

    7. When to Use Node.js vs PHP

    Choose PHP when:

    • You are building a WordPress site or WooCommerce store
    • Your team already knows PHP or Laravel
    • You need a simple content website or blog
    • You are working with shared hosting that only supports PHP
    • You need deep integration with a CMS ecosystem

    Choose Node.js when:

    • You are building a REST API or GraphQL API
    • You need real-time features (chat, live notifications, WebSockets)
    • You are building a microservices architecture
    • Your frontend is React or Vue and you want to share code between front and back end
    • You expect many concurrent connections

    Real-world tip: Many modern projects use both. WordPress on PHP handles the public-facing site, while a Node.js service handles real-time features or a separate API layer. As a developer who knows both, you become twice as valuable.

    8. Next Steps for PHP Developers

    1. Install Node.js — Download from nodejs.org (LTS version recommended)
    2. Learn JavaScript ES6+ — Arrow functions, destructuring, template literals, and Promises are essential
    3. Build a small REST API with Express.js — Create CRUD endpoints for a simple resource
    4. Connect a database — Try mysql2 (familiar to PHP devs) or mongoose for MongoDB
    5. Learn async/await deeply — This is the heart of Node.js code quality
    6. Explore environment variables with the dotenv package — Same concept as .env in Laravel
    7. Study Express middleware — It works just like Laravel middleware

    The learning curve is real, but as someone who already understands web fundamentals, HTTP, databases, and server-side programming — you are already 60% of the way there.

    Conclusion

    Node.js is not a replacement for PHP — it is a complementary tool that opens new doors. By learning both, you can tackle a wider range of projects: from WordPress development to real-time applications and REST APIs.

    Have questions or want to see a follow-up on a specific topic? contact me directly.