Node.js in Action: Understand "os" Module in Node.js

Node.js in Action: understand "os" module in node.js

This is the node.js in action article series. This series is explaining node.js. In our previous articles we have covered many things, you can read them here.

This article explains the important node.js module called "os". This is module is necessary in day to day node.js application development. To understand it a basic understanding of node.js and its modules is needed. So if you don't have that then I suggest you go through our previous articles.

Using the "os" module, we are able to access the operating system and server related information. There are many functions that provide the information. Let's have a quick look at a few of those functions.

os.tmpdir()

Returns the operating system's default directory for temp files.

os.endianness()

Returns the endianness of the CPU. Possible values are "BE" or "LE".

os.hostname()

Returns the hostname of the operating system.

os.type()

Returns the operating system name.

os.platform()

Returns the operating system platform.

os.arch()

Returns the operating system CPU architecture.

os.release()

Returns the operating system release.

os.uptime()

Returns the system uptime in seconds.

os.loadavg()

Returns an array containing the 1, 5, and 15 minute load averages.

Let's implement a few functions in an example. I hope the node server is up and running in your system and everything is just fine. Let's build your server with the following code.

var http = require('http');
var os = require(
'os');
var server = http.createServer(function (req,res) {
console.log(
'Tempurary directory name: ' + os.tmpdir());
console.log(
'Hostname is: ' + os.hostname());
console.log(
'OS type is: ' + os.type());
console.log(
'Platfomr is :' + os.platform());
console.log(
'Uptime is :' + os.uptime());
});
server.listen(9090);
console.log(
'server running...')

Within the server code we are calling various functions defined in the "os" module. Here is sample output of this code.


Conclusion

In this small article we have understood the "os" module with a practical example. This module will give information related to "os" and it's important when we write OS specific code in an application. In a future article we will look at a few more in built-in modules of node.js. Happy learning.


Recommended Free Ebook
Similar Articles