Let’s dive into this module with an example. Assume that you have to know if your application runs on Node.js or Rhino. This could be easily done by checking the type of the
global variable. In Node.js it is an object whereas Rhino provides a function. Boom! There you go. You can formulate a condition now! But what if you also need to know if your application is running in a browser? Well, game over. Too complicated. The good news is you don’t have to do such things anymore.
- The name of the platform (e.g. Google Chrome, Node.js, etc.)
- The version of the platform
- The rendering engine (of the browser; e.g. Gecko, Trident, etc.)
- The manufacturer of the product (e.g. Apple)
- The name of the product (e.g. iPhone, Kindle, etc.)
- The name of the operating system (e.g. iOS 7.0, Mac OS X 10.7.2, etc.)
- The architecture the operating system is build for (e.g. ia32, etc.)
npm install platform
The API for using platform.js is consistent. What differs is the module loading procedure. Consider the README for a brief explanation about how to use the library with an AMD loader for instance. The following usage example refers to Node.js:
'use strict'; var platform = require('platform'); console.log(platform.name); // e.g. Node.js console.log(platform.version); // e.g. 0.10.26 console.log(platform.os.architecture); // e.g. 32 console.log(platform.os.family); // e.g. Linux console.log(platform.description); // e.g. Node.js 0.10.26 on Linux
The library provides also a function with which you are able to parse an user agent string:
'use strict'; var platform = require('platform'); var ua = 'Mozilla/5.0 (X11; Linux i686; rv:30.0) Gecko/20100101 Firefox/30.0'; var browser = platform.parse(ua); console.log('Result from parsing the user agent string: %s n', ua); console.log(browser.name); // Firefox console.log(browser.description); // Firefox 30.0 on Linux i686 console.log(browser.version); // 30.0 console.log(browser.layout); // Gecko console.log(browser.os.family); // Linux i686
If you curious to see how it performs in a browser environment, check out this codepen.
I’m pretty sure that you have several use cases in mind where you could use platform.js, but one warning: Don’t see it as a replacement of feature detection libraries. True to the motto: If it is a Gecko-based rendering engine (because browsers with this engine have all the shiny new features) then I could use
navigator.getUserMedia(). Never ever make such assumptions. Look at it more in a way to
- display a tailor-made UI.
- collect statistical data about the devices of your users.
- lazy import own platform-specific modules (e.g. Node.js modules).
platform.js is a powerful gift when it comes to determining exactly in which environment your application is running. That means, we do not have to write “if-else-if-else-if” statements anymore, folks. We have a rock-solid foundation now!