caharkness.com

Home · Contact · Git


Is Node.js Useless?

  • Short answer:

    • Mostly.
  • Long answer:

    • I would never recommend Node.js because writing JavaScript is a sloppy language. However, as a full-stack software engineer and system administrator, I recommend installing the Node.js runtime for one utility: PM2.

Why PM2?

PM2 makes daemonizing processes very easy. Most virtual machines I spin up are single-user Debian environments. I would rather use PM2 to host my server software spawned in by a shell script rather than doing this the systemd way. You can think of PM2 as giving you the "daemonize this" command.

For example:

pm2 start my-script.sh

Whatever my-script.sh is doing, PM2 will ensure that it continues to run in the background. Should you want my-script.sh to run automatically at startup, easy. Just run the commands below:

pm2 startup
pm2 save

When run as root, this will tell PM2 to start its list of processes when the system boots with no extra fuss. Want to see what's currently running under PM2? Run:

pm2 list

Seriously. The task of managing daemonized processes has never been easier. Here's how you prepare your Debian system to have Node.js and PM2:

apt install nodejs
apt install npm
npm install -g n
n latest
npm install -g pm2

This installs Node.js, the Node package manager, and the "n" utility for making sure that you are using the latest version of Node.js.

Now what?

Now that you have PM2, it's time to start hosting your microservices written in Python and PHP. I use shell scripting to spawn the processes like so:


PHP:

#!/bin/bash

# https://stackoverflow.com/a/1482133
SCRIPT_DIR="$(dirname -- "$(readlink -f -- "$0";)";)"
cd "${SCRIPT_DIR}"

# Allow port setting via first argument:
PORT=8000
if [[ ! "$1" == "" ]]
then
    PORT="$1"
fi

# Handle multiple simultaneous requests in Linux only:
export PHP_CLI_SERVER_WORKERS=4

php -S 0.0.0.0:$PORT index.php --enable-mbstring

Python:

#!/bin/bash

INSTALLATION=0

if [[ ! -d venv ]]
then
    python3 -m venv venv || python -m venv venv || (
        echo "Could not create a Python virtual environment."
        exit 1
    )

    INSTALLATION=1
fi

if [[ -f ./venv/bin/activate ]]; then source ./venv/bin/activate; fi
if [[ -f ./venv/Scripts/activate ]]; then source ./venv/Scripts/activate; fi


if [[ $INSTALLATION -eq 1 ]]
then
    pip install discord.py
    pip install pillow
fi

python -u bot.py