Category Archives: Learn coding

Migrating Node.js app running under root to run under a non-root user

On Linux, if you want to open a port less than 1025, you normally need to run as root. Running a web application (runs on port 80/443, in the above range) entirely under root user is really dangerous and is obviously not recommended.

Most of web servers only run a master process as root and delegates works to other helper processes which run with lower privileges to perform. But Node.js runs with single-process model, then if you plan to run Node.js in Linux systems it’s a little bit tricky to deal with the port issue.

Fortunately, on modern releases of Linux, you can use capabilities setting to work out of that. You only need the root access to install and setup the capabilities setting to tell the system to allow Node.js binding services on low ports ( port # < 1025)

Commands to do that are very straight forward and simple:
Install the capabilities tool:

$ sudo apt-get install libcap2-bin</i> 

Grant Node.js to bind services on low ports:

$ sudo setcap cap_net_bind_service=+ep <Path to Node.js> Eg: /usr/nodejs/bin/node

And now you can run node.js without having to sudo to root

But what if you already installed and run your application under root, and you want to switch everything over to a lower privileged user? That’s also quite easy with following steps:

  • Create a new user
  • $ useradd node_app -G nodegroup
  • Copy your web application directories to another place
  • $ cp -R /path/to/the/app /new/destination/
  • Change owner of the directories to the node_app:nodegroup under which you want your app runs
  • $chown -R node_app:nodegroup /new/destination/
  • Change the owner of node.js run time directories to the new user:group
  • $chown -R node_app /user/nodejs
  • Run the capabilities setting commands above

That’s it.

List files using Node.js

Neat code snippetĀ  to recursively list files of a directory using Node.js

/* Bad error handling though ...*/
var fs = require('fs');
var path = require('path');
var dirToList = 'path/to/dir';
var listFiles = function(dir) {
  fs.readdir(dir, function(error, items) {
    for (var index in items) {
      var filePath = path.join(dir, items[index]);
      (function(fullFilePath) {
        fs.stat(fullFilePath, function(error, stats) {
          if (stats && stats.isFile()) {
            console.log(fullFilePath);
          } else if (stats && stats.isDirectory()) {
            listFiles(fullFilePath);
          }
        })
      })(filePath);
    }
  })
}
listFiles(dirToList);