JS Tip of the Day: JavaScript Outside the Browser: Node

JavaScript Outside the Browser: Node

Back in 1995 JavaScript was first released to the world through the Netscape browser. Even now, when we think of JavaScript we immediately gravitate to the browser as being the environment in which it runs. What you may not realize, is that only a few short months after shipping the first browser to support JavaScript, Netscape also released a server capable of running JavaScript. So while JavaScript has been humming along inside browsers for decades now, so too, has it been able to run outside of them (i.e. on a server). It wasn’t until more recently that JavaScript’s use outside of the browser started to really take off. That was in no small part thanks to the release of Node.

Node is a cross-platform, browser-less JavaScript runtime based on Chrome’s V8 engine - the same engine used in the execution of JavaScript in the Chrome browser. It is used not only for running servers - as Netscape had done so many years ago - but also any number of desktop applications, including playing a large role in today’s modern JavaScript development environments.

JavaScript running in Node can be quite different than JavaScript running in the browser. Not only do you lose access to web APIs like the window or document objects, but you also gain access to brand new APIs that do not exist in the browser. These include APIs like the file API for directly accessing files on your computer, something code running in browsers cannot do.

// running in Node
let fs = require('fs');

fs.writeFileSync('hi.txt', 'Hello, file!'); // file saved to drive
let fileContents = fs.readFileSync('hi.txt', 'utf8');
console.log(fileContents); // Hello, file!

Even if you’re not writing JavaScript code to run in Node yourself, having Node installed on your system gives you the ability to run any of the massive number of JavaScript applications written for it. And in using the Node Package Manager, or NPM, you’re able to access to a massive collection of JavaScript packages and libraries for use in your own projects, even when your project is targeting JavaScript running in the browser.

More info