Two useful methods of the os module in Node.js

Although it's not frequently used, the os module of Node.js contains some interesting and useful methods. Two of them are the platform(), which returns the type of the operating system, and the cpus(), which gives more information about the CPU cores of the computer

The os module is a core module of Node.js, and as such, it doesn’t need to be separately installed.

1. platform()

One of the methods os has and can sometimes be very useful is platform.

platform returns a string representing the operating system (Linux, Windows or Mac) on which Node.js is running. Node.js currently supports seven return values and additionally, it might return android, but Android support in Node.js is still in the experimental phase. For the full list of return values please see the link above.

1.1. Example

We can start by requireing os and logging the return value:

const os = require('os')

console.log(os.platform())  // 'win32'

If your operating system is Linux, the method will return linux, and darwin will be given back on Mac.

1.2. Use case

I play around with libraries and apps on both of my Windows and Linux computer at times, and set up a GitHub repo for the code. To avoid changing platform specific code, I use the platform method.

Assume that we are building a server with a database connection, and we use Docker for creating the database instance.

Sadly, Docker doesn’t recognize localhost on Windows, just like it does on Linux or Mac. Instead, it connects to 192.168.99.100, and if we want to make the app platform compatible, we can use platform for getting the database path.

For the following code to work, you will need Docker installed. Please see the Docker website on the installation instructions.

First, let’s set up a database, say MongoDB, which is a very popular NoSQL database.

To run the container, we can go to the terminal and type docker run -d -p 27017:27017 -v mongo-data:/data/db mongo:latest. This command will start a MongoDB database instance in the background (-d), opens port 27017 both on the host (the computer) and inside the container, and binds a named volume (mongo-data) to the container’s /data/db folder. The latest MongoDB image is used to start the container (mongo:latest).

We can now write some code to connect to the database. A very popular library which is often used with MongoDB is Mongoose, and it can be installed using npm install mongoose in the project folder (after npm init has been run).

We can connect to the MongoDB database like this:

const { platform } = require('os')
const mongoose = require('mongoose')

const dbPath = platform() === 'win32'
  ? 'mongodb://192.168.99.100:27017/os-test-db'
  : 'mongodb://localhost:27017/os-test-db'

mongoose
  .connect(dbPath, { useNewUrlParser: true })
  .then(() => {
    console.log('Connected to database')
  })
  .catch(err => {
    console.error('Error while connecting to database')
  })

We can use object destructuring to get the platform method from the os module.

As it was stated above, if the operating system is Windows, platform will return win32.

The dbPath string will depend on the operating system, and we can use this string to connect to the database, which has the name of os-test-db.

If the above code is run, the Connected to database success message should be written to the console.

2. cpus()

Another useful method of the os module is cpus, which returns an array of objects with some useful pieces of information on each CPU core. Each object contains properties on the model and the speed of the CPU, and some other interesting and exciting facts.

2.1. Use case

cpus can be used along with the cluster module when scaling Node.js, and we can spawn several processes, typically one for each core making use of the capacity of the CPU.

The code can look like this:

const { cpus } = require('os')
const cluster = require('cluster')
const http = require('http')

if (cluster.isMaster) {
  console.log(`Master process pid ${ process.pid } is running`)

  const numberOfCPUs = cpus().length
  console.log(`This computer has a  ${ numberOfCPUs } CPU core(s)`)

  cpus().forEach((cpu) => {
    cluster.fork()
  })

  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${ worker.process.id } is down with code ${ code }.`)
  })
} else {
  console.log(`Worker ${process.id} is running`)
  http.createServer((req, res) => {
    res.end(`Response from process ${ process.id } \n`)
  }).listen(3000)
}

cluster has a property called isMaster, which indicates if the process is the master process. If so, we can call the cpus method, which returns an array.

The number of objects in the array will be equal to the number of cores, and for each core, we can create a new child (worker) process (fork).

Each worker process can run a server and has a different process id. If port 3000 (the one the server listens to) is accessed in the browser by typing localhost:3000 a couple of times, there’s a chance that a different process will respond each time.

3. Conclusion

os is a small and not very often used module, although it contains some useful methods and properties.

Two of these are platform and cpus, which return the type of the operating system and an array with information on the CPU, respectively.

The os module has a few more to offer, please see the documentation for the full list.

Thanks for reading, and see you next time.