Introduction to Node.js and how to run JavaScript outside the browser.
Posted
Updated
Europe’s developer-focused job platform
Let companies apply to you
Developer-focused, salary and tech stack upfront.
Just one profile, no job applications!
This article is based on Node v16.14.0 and nvm v0.35.
Node.js is a free, open-sourced, cross-platform JavaScript run-time environment that lets developers write command line tools and server-side scripts outside of a browser. The runtime is built on Chrome's V8 JavaScript engine and was created by Ryan Dhal in 2009.
💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.
Since it's creation it got very popular and plays an important part in the development of web applications, but not only there, since you can build almost everything with it. The team who created Node.js took the core of Google Chrome, the V8 JavaScript engine, to run outside the browser. This gives Node.js the ability to leverage the work from Google engineers who build the Chrome V8 and it makes the runtime blazing fast and benefits from performance improvements and just-in-time compilations. In a nutshell, JavaScript code running in Node.js is very performant.
Node.js is an asynchronous event-driven JavaScript runtime and designed to build scalable applications.
A Node.js app is running in a single process, without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives that prevent JavaScript code from blocking. Libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.
When Node.js performs an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.
This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.
Read more about performance in the official docs.
Additionally, you can use the new ECMAScript standards without problems, as you don’t have to wait for all your users to update their browsers - you are in charge of deciding which ECMAScript version to use by changing the Node.js version, and you can also enable specific experimental features by running Node with flags.
There are several, different ways to install Node.js. The two most used ones are:
The easiest way to install Nodejs is from source, but this limits your option to have multiple versions of Nodejs installed. It can maybe cause permission errors in future projects. If you just want to use one version of Node:
node --version
to see if it was successfully installed.The recommended way to install Node is via NVM (Node Version Manager). The Node Version Manager is a bash script used to manage multiple released Node.js versions. It allows you to perform operations like install, uninstall, switch version, etc.
On Linux run the following commands:
apk add -U curl bash ca-certificates openssl ncurses coreutils python2 make gcc g++ libgcc linux-headers grep util-linux binutils findutils
curl -o- | bash https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh
nvm install --lts
For macOS and Windows, please refer to the official docs.
You can use the REPL or the CLI.
REPL also known as Read Evaluate Print Loop is a programming language environment, that takes single expression as user input and returns the result back to the console after execution.
You can use the interactive REPL for playing around, think of it as the console in the browser, or a console window.
node
in your terminal, and you will see that the welcome line
Welcome to Node.js v15.7.0. Type ".help" for more information.
..exit
The usual way to run a Node.js program is to run the node globally available command, once you've installed Node.js, and pass the name of the file you want to execute.
If your main Node.js application file is app.js, you can call it by typing:
node app.js
will run your app.js file.
While running the command, make sure you are in the same directory which contains the app.js file.
This example is a simple Hello World
server.
Create a file named app.js.
touch app.js
Copy the code below into the file app.js.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Now, run your web server using node app.js
in the terminal, you have to be in the same folder, where the file app.js is located.
Visit http://localhost:3000
and you will see a message saying "Hello World".
By using a framework, you can work with a set of tools, guidelines, and recommended practices that help you save time and boost productivity.
Selecting a Node.js framework can be a bit tricky and subjective to its use case, because we choose based on a particular feature. This can is ranging from the weight of the framework on the application, speed, simplicity, learning curve, flexibility and configuration, use case or maybe even popularity in some cases. A friendly reminder: Github Stars aren't everything.
The following five Node.js frameworks I can highly recommend:
Express.js is a fast, non-opinionated, minimalist web framework for Node.js and the most popular one. It behaves like a middleware to help manage servers and routes. It has a minimalist approach, is not opinionated and is focused on the core features of a server.
Meteor is a very powerful full-stack framework, powering you with an isomorphic approach to building apps with JavaScript, sharing code on the client and the server. It’s major advantage is it’s realtime update, when changes occur on the web app, it automatically updates the template with the latest changes.
Koa.js is built by the same team behind Express.js, and it aims to be even simpler and smaller. Koa does not bundle any middleware within core, meaning the middlewares are more cascaded/streamlined, thereby allowing you to structure the parts however you want(component-based middlewares). This makes the framework to have more control over configurations and handling.
Next.js is a framework to render server-side rendered React applications, and it got a massive boost in 2020.
Socket.io a real-time communication engine to build network applications.
Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut.
If you want to know more about Node, have a look at these Node Tutorials.
References (and Big thanks):
Never miss an article.