Node.js inside-out - Modules API rediscovery...

Node.js inside-out - Modules API rediscovery...

<strong>Since its first release in 2011, Node.js has greatly changed, or should I say revolutionizedJavaScript development and its use-cases. Being able to write code in their favorite language, and run in on the server-side, many web developer quickly notice the huge potential of the project. Fast forward to 2019 and Node.js is one of the most beloved and used runtimes in the entire programming market. It's fast (thanks to V8), reliable and easy to use. And, with its own NPM package manager 📦, it has the biggest collection of open source libraries and tools in the world! These facts alone tell something about how popular Node.js has become.</strong>

Since its first release in 2011, Node.js has greatly changed, or should I say revolutionizedJavaScript development and its use-cases. Being able to write code in their favorite language, and run in on the server-side, many web developer quickly notice the huge potential of the project. Fast forward to 2019 and Node.js is one of the most beloved and used runtimes in the entire programming market. It's fast (thanks to V8), reliable and easy to use. And, with its own NPM package manager 📦, it has the biggest collection of open source libraries and tools in the world! These facts alone tell something about how popular Node.js has become.

For reasons above, in this series titled “Node.js inside-out”! we’re going to explore everything about the project. We’ll talk about what Node.js actually is and what APIs in-depth it provides. With the rise of NPM and number of Node.js frameworks, many developers prefer that instead of the lower-level stuff that Node.js itself provides. 👏 Don’t get me wrong - it’s fine to use various tools that made your development more enjoyable. It’s just that sometimes, when you need to squeeze some additional performance or want to know what’s going on under-the-hood, then it’s good to get back to the basics. Sadly, many people omit this step when starting with Node.js (unlike the web development - JS, HTML and CSS are standard milestones for beginners), going straight to using different frameworks without really understanding them or their true potential.

With this intro finally behind us, as I said, I’d like this series to provide an alternative, more beginner-friendly Node.js super-in-depth introduction in slightly more… acceptable way. 😉 So, I hope you’ll enjoy it and learn something new!

What exactly is Node.js?

For start - a bit of theory… but not really boring one. 😃 Node.js itself is a runtime environmentfor JavaScript. It’s open-source and cross-platform. Its development started in 2009, with the first official release in 2011. The idea behind it was simple - to allow JS to run in different environments than the browser. It’s nothing that hasn’t been done before, just not with that big success. Today its development is overseen by the Node.js foundation with additional help from a big number of contributors. It’s used by many big names in the industry and doesn’t seem to stop evolving and improving with time.

As a runtime environment, Node.js is powered by V8 🔋 - open-source JS engine (the fastest on the market), originally created by Google. Thus, it’s working similarly to any Chromium-basedbrowser. The code is run in an event loop, on a single thread. The asynchronous I/O allows it to take care of multiple concurrent operations. ⚡ This approach has its downsides, but they’re related to JS in general.

Node.js also provides a lot of APIs for developers to use. They allow accessing features that aren’t possible through everyday browsers. They’re provided in the form of modules, as a standard way to handle core functionalities. Their features vary greatly - from file system access and cryptography to C++ add-onschild processes, and V8 access. We’ll explore each of these later on in the series. 👍

With Node.js rapid development, more and more interesting tools appeared. With its robust architecture, you can create server-side codeCLI toolsreal-time applications, which further means likes of games, social media and others! Of course, it’s all possible with the combination of client-side, which can be written, utilizing your current knowledge, in JS too! But I don’t only mean browsers! Based on, inspired by or built with Node.js, tools like Electronor NativeScript came to exist. Basically what they do is allow you to create fully native desktop or mobile applications… with JavaScript! And, IMHO, that was the key to Node.js success - one, single language to rule 'em all! ✊

Node.js APIs

I’d like to commit the rest of this series to explore different APIs of Node.js. We’ll start with the (ECMAScriptModules API. I think that’s a good-enough choice for the beginning. 😃 Modules are used almost everywhere, but you could be surprised by how many (possibly) unknown features they possess in Node.js. But, if you think this is too easy, then fear not! We’ll explore more advanced APIs in future posts! And, as a side-note - I’m using Node.js v10.15.3 - latest stable LTS version for the rest of this tutorial. Now, let’s get started! 🎉

Modules

Probably almost all of today’s web developers use some kind of module system to better organize their code. The most popular options being ES modules (newest standard) and CommonJS format (the one used in Node.js). But there’s a little more to Node.js module system that just importing and exporting stuff. 😅 And that’s what we’re going to explore!

CommonJS

Let’s first recall the rules of CommonJS (CJS) module format - the main one in Node.js. In Node.js, unlike in any other front-end TypeScript or Babel-based workflow, modules are real things. Your imports and exports are resolved at runtime - not at any kind of transpilation step. Your basically getting is a real module system. 😮 This, naturally, has its pros as well as cons. But, transpliation is still a nice option to have (especially when, e.g. doing micro-optimizations and not wanting to resolve modules at runtime) you can easily use Babel or any other tool you want - anytime anyhow! 😉

I guess many people refer to CJS as the one with require() syntax. That’s because this particular keyword is probably the most recognizable symbol for this format.

Import / export

For exporting you can assign your value to the special module.exports property to respective properties when dealing with objects. For the second purpose, you can also use the exports object - a quick shortcut. Just don’t mess the two when assigning single values - exports won’t work with stuff like that! That’s because exports is, in fact, a reference to modules.exports, which defaults to empty object.

// module1.js
exports.numberValue = 10;
exports.stringValue = 'str';

// module2.js
module.exports = () => {
// code
}

Notice, that the arrow function ➡ syntax (and many other ES-Next features) is natively supported by Node.js (and other V8-based browsers).

Imports can be done with well-known require() syntax:

const module1 = require('module1.js');
const module2 = require('module2.js');

module1.numberValue; // 10
module1.stringValue; // 'str'
module2();

I think it’s a well-known fact that the syntax above can be freely used to import core Node.js modules (like fs or path), modules located in relative paths ( ./ ), node_modules directory, but also the global ones. Also, you can feel free to omit your .js.json or .node (for native add-ons) file extensions. Or use the index.js files as folders’ main files and etc. Just the usual stuff related to JS modules. Most of the times, it goes unnoticed… ⚡

Wrappers & globals

Everything above is just pure basics. You can easily go and use that without any further understanding. But, in this series, we’re digging deep! And so, we want to know what require()module and exports really are.

Before execution, code from each imported module is put inside a wrapper function 🌯, looking something like this:

((exports, require, module, __filename, __dirname) => {
// module code
});

This is a very important concept to understand, and that’s for 2 main reasons:

  1. All what-seems-like global variables and other user-defined variables at the top scope of different modules are preserved in limited, module-only scope. You have to use module.exportsexports to actually output something to the outer world. 📤
  2. This perfectly shows us where our require() function and module object actually come from. It also hides from developers the fact of function wrappers in a nice form of what-seems-like globals. 👍

With that said, I think it’s a perfect time to explore what parameters of our top wrapper really do:

  • exports - just a reference to module.exports (as said before);
  • require() - function used to import modules. It has some additional properties of its own:
  • cache - object where all loaded modules are cached (more on that later);
  • main - reference to a Module object representing entry module;
  • resolve() - returns the exact filename (complete path) to the file that the module would be imported from when using require() with the same argument:
  • paths() - returns an array of paths searched through when locating the provided module;
  • module - a reference to the object (Module instance) representing the current module:
  • children - an array of modules first imported in the given module;
  • exports - an object used to export values from the given module;
  • filename - absolute path to the given module;
  • id - identifier for the given module. Usually equal to the filename (example exception being index files);
  • loaded - indicating whether the module has already loaded. Especially important when using multiple requires in different places i.e. cycles. Ensure that they’re properly loaded first;
  • parent - reference to the module that has loaded given module first;
  • paths - an array of paths searched through when locating the given module;
  • require() - provides a way to call require as if it was from the given module;
  • filename - an absolute path of the module;
  • dirname - directory name of the module;

Feels a bit like docs, does it? 😅 Hopefully it’s not bad. I tried to provide it in a form that’s both more understandable, shorter and simpler than the official documentation. The main point is just to understand where these seeming globals come from and what do they do. You’d most likely hardly-ever use any of properties above. Noticeable exceptions (beyond import/export syntax) include__dirname and __filename which many beginners may not know where they come from and what do they represent. Well, now you know. 😉

The Module (capped letter on purpose) is a structure that all modules instances mentioned above inherit from. Node.js allows you to access this as well, in a form of core module module 😂 (require('module')). It has even fewer use-cases than the API above, as it provides only two additional properties:

  • builtinModules - an array of Node.js built-in modules’ names;
  • createRequireFromPath() - allows creating a relative requires that resolves to start from provided path, e.g. folder. Useful when using multiple imports from the same directory while not limiting readability;

As you can see, the properties above have their really, really specific use-cases. As such, I’d consider them more as internal properties rather than general-use ones. 😅 Although, if you’re developing a Node.js framework… who knows? 🤔

Caching

The last thing to note about modules is that they’re cached. This has a huge impact on how they work and the performance of actually loading them. Once loaded, your module won’t have to be reloaded the second time. Instead, its cached version will be used (stored in object referenced by require.cache). This results in improved performance, but also has some additional, sometimes taken-as-granted, side-effects. You see, when a module is first loaded (that’s why the children and parent properties of module exist BTW, because they indicate specific relations between modules, i.e. where it was first loaded and thus cached), cached and then accessed, all of its code has been executed once and all exports of this module are carried throughout all files that imported given module. This allows for some cunning tricks, like a dedicated module for semi-globals (values that can be imported anywhere and changed, affecting other modules). 🛸

Of course, you can force reload of a module by messing with require.cache object and removing given module (by its id). But, it’s not really recommended practice - unless you’re sure that this is exactly what you want.

ECMAScript Modules

Up to this point, we were talking only about CJS modules. But, as many web developer should now, there has been a new standard introduced in 2015 with ES6 (not that new any longer, huh? 😅) which is referred to as ECMAScript Modules (ESM for short). They’re the ones who brought us this fine import/export syntax and finally an industry-grade standard! Sadly, as we’ve already seen with Node.js itself, the old standards (CJS, AMD, etc.) still prevail in some, even as actively-developed places as Node. But, this has finally changed with the release of Node v8.xwhere support for ESM was introduced, although with an experimental flag ☢ (which stayed to current v11.x so far). But, that’s not something that would stop us from taking a closer look at ESM in Node.js, is it? 👍

Enable

As much as experimental status may not bother you (apart from some features still needed to be implemented or improved), it comes with some additional requirements. ESM (at the time of writing) isn’t supported out-of-the-box. You have to use --experimental-modules flag to properly enable them whenever running Node. Also, you have to use the .mjs extension for your files to be properly loaded through ESM system. 👉

Quite frankly, ESM is mostly backward-compatible with CJS (with some API differences), meaning that you can freely import CJS modules through ESM without much hassle. On the other hand, what you cannot do, is importing ESM modules with CJS syntax. This is not allowed, as CJS uses different resolving method and timing (not forward-compatible 😅). Of course, the JSON files and C++ modules/native addons can freely be used with the ESM syntax.

Differences

Beyond cross-compatibility, there are a couple more differences between Node.js CJS and ESM implementations. ESM has completely different resolving system, based on URL and file: protocol. This means that you can e.g. pass additional query parameters to indicate that the following module should be loaded again (instead of using its cached version). 💾

import module from './module1.js?id=1';
import moduleClone from './module1.js?id=2';

For now, the external URL cannot be used. Although with schematics above, it may be possible in the near future.

The URL format is also used to identify modules inside cache (that’s why the example above works). But, as we don’t have access to the same values available to us as in CJS (require()module, etc.) the cache object is stored separately. Also, unlike CJS, ESM doesn’t resolve NODE_PATH, which further means no way of importing globally-installed modules.

And finally, at its current state, import provides one property of its own. It’s an object called import.meta which, again, has one property called import.meta.url, indicating the absolute URL of the current module.

import.meta.url

Hooks

The last new feature of Node.js ESM is called loader hooks. ⚡ As the name suggests, these hooks allow you to intercept the loading process of ESM modules with your own, custom code. 👏

There are 2 possible hooks for you to use - resolve() and dynamicInstantiate(). You can provide one or both of those in a form of asynchronous functions, in a single, separate JS file. You later can load and use them with a simple CLI argument:

node --experimental-modules --loader ./loader.mjs ./index.mjs

The resolve() hook takes 3 parameters:

  • specifier - an absolute path of the current module’s file;
  • parentModuleURL - URL of the parent module (the one that loaded given module first). It follows file: protocol and defaults to undefined when used on the entry module (there’s no parent);
  • defaultResolve() - default resolve function;

After appropriate processing, your resolve hook should return an object with two properties: urland format. The first indicates the URL resolved for the handled module (file:) and second - module’s format. 📦 While url is a no-brainer, format has a form of a string with 6 possible values:

  • "esm" - indicates ESM module;
  • "cjs" - indicates CJS module;
  • "builtin" - indicates Node.js built-in modules, e.g. http or path;
  • "json" - indicates JSON file;
  • "addon" - indicates a C++ native addon;
  • "dynamic" - indicates the use of dynamicInstantiate hook;

The dynamicInstantiate() hook allows you to properly handle modules with "dynamic" format. The hook itself is an async function taking a single url argument (URL of the handled module), that should return an object with 2 properties:

  • exports - an array of names for exported properties;
  • execute() - functions taking above exports as an argument. It should access the previously defined property names on exports object and interact with them using .get() and .set() methods accordingly. It will be later executed at the time of module evaluation;

In general, this hook gives you an option to provide a somewhat alternative form for modules that require that (e.g. different file extensions). Just keep in mind that it doesn’t have to be limited to just setting completely different properties - you can use the provided URL to load and evaluate the file the way you want. As always in programming - options are almost endless*! 😉

We’re just getting started!

Yup, it’s been a while and we only managed to cover Modules API - just bare modules! Seemingly such a simple thing and has so much depth to it! 🤔 Again, don’t worry, there’s some even more interesting stuff in stock! I’m planning on covering the File System API next (that’s the big one!), but maybe you’d like to see something else? I’m very much open to different options! And remember that I plan on covering all Node.js APIs eventually!

So, let me know down in the comments what do you think about this article and what would you like to see next! Also, share this post with other for reach! 😃 As always, follow me on Twitteron my Facebook page and consider checking out my personal blog to keep up-to-date with the latest content about this series and other awesome JS stuff! 🛸 Thanks for reading and I see you in the next post!

Originally published by Areknawo at https://areknawo.com

Learn More

☞ The Complete Node.js Developer Course (2nd Edition)

☞ Learn and Understand NodeJS

☞ Node JS: Advanced Concepts

☞ GraphQL: Learning GraphQL with Node.Js

☞ Angular (Angular 2+) & NodeJS - The MEAN Stack Guide

☞ Beginner Full Stack Web Development: HTML, CSS, React & Node

☞ Node with React: Fullstack Web Development

☞ MERN Stack Front To Back: Full Stack React, Redux & Node.js

☞ Building MongoDB Dashboard using Node.js

☞ Run your Node.js application on a headless Raspberry Pi

How to Use Express.js, Node.js and MongoDB.js

How to Use Express.js, Node.js and MongoDB.js

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

Creating a Node Application

To get started I would recommend creating a new database that will contain our application. For this demo I am creating a directory called node-demo. After creating the directory you will need to change into that directory.

mkdir node-demo
cd node-demo

Once we are in the directory we will need to create an application and we can do this by running the command
npm init

This will ask you a series of questions. Here are the answers I gave to the prompts.

The first step is to create a file that will contain our code for our Node.js server.

touch app.js

In our app.js we are going to add the following code to build a very simple Node.js Application.

var express = require("express");
var app = express();
var port = 3000;
 
app.get("/", (req, res) => {
&nbsp;&nbsp;res.send("Hello World");
});
 
app.listen(port, () => {
  console.log("Server listening on port " + port);
});

What the code does is require the express.js application. It then creates app by calling express. We define our port to be 3000.

The app.use line will listen to requests from the browser and will return the text “Hello World” back to the browser.

The last line actually starts the server and tells it to listen on port 3000.

Installing Express

Our app.js required the Express.js module. We need to install express in order for this to work properly. Go to your terminal and enter this command.

npm install express --save

This command will install the express module into our package.json. The module is installed as a dependency in our package.json as shown below.

To test our application you can go to the terminal and enter the command

node app.js

Open up a browser and navigate to the url http://localhost:3000

You will see the following in your browser

Creating Website to Save Data to MongoDB Database

Instead of showing the text “Hello World” when people view your application, what we want to do is to show a place for user to save data to the database.

We are going to allow users to enter a first name and a last name that we will be saving in the database.

To do this we will need to create a basic HTML file. In your terminal enter the following command to create an index.html file.

touch index.html

In our index.html file we will be creating an input filed where users can input data that they want to have stored in the database. We will also need a button for users to click on that will add the data to the database.

Here is what our index.html file looks like.

<!DOCTYPE html>
<html>
  <head>
    <title>Intro to Node and MongoDB<title>
  <head>

  <body>
    <h1>Into to Node and MongoDB<&#47;h1>
    <form method="post" action="/addname">
      <label>Enter Your Name<&#47;label><br>
      <input type="text" name="firstName" placeholder="Enter first name..." required>
      <input type="text" name="lastName" placeholder="Enter last name..." required>
      <input type="submit" value="Add Name">
    </form>
  <body>
<html>

If you are familiar with HTML, you will not find anything unusual in our code for our index.html file. We are creating a form where users can input their first name and last name and then click an “Add Name” button.

The form will do a post call to the /addname endpoint. We will be talking about endpoints and post later in this tutorial.

Displaying our Website to Users

We were previously displaying the text “Hello World” to users when they visited our website. Now we want to display our html file that we created. To do this we will need to change the app.use line our our app.js file.

We will be using the sendFile command to show the index.html file. We will need to tell the server exactly where to find the index.html file. We can do that by using a node global call __dirname. The __dirname will provide the current directly where the command was run. We will then append the path to our index.html file.

The app.use lines will need to be changed to
app.use("/", (req, res) => {   res.sendFile(__dirname + "/index.html"); });

Once you have saved your app.js file, we can test it by going to terminal and running node app.js

Open your browser and navigate to “http://localhost:3000”. You will see the following

Connecting to the Database

Now we need to add our database to the application. We will be connecting to a MongoDB database. I am assuming that you already have MongoDB installed and running on your computer.

To connect to the MongoDB database we are going to use a module called Mongoose. We will need to install mongoose module just like we did with express. Go to your terminal and enter the following command.
npm install mongoose --save

This will install the mongoose model and add it as a dependency in our package.json.

Connecting to the Database

Now that we have the mongoose module installed, we need to connect to the database in our app.js file. MongoDB, by default, runs on port 27017. You connect to the database by telling it the location of the database and the name of the database.

In our app.js file after the line for the port and before the app.use line, enter the following two lines to get access to mongoose and to connect to the database. For the database, I am going to use “node-demo”.

var mongoose = require("mongoose"); mongoose.Promise = global.Promise; mongoose.connect("mongodb://localhost:27017/node-demo");

Creating a Database Schema

Once the user enters data in the input field and clicks the add button, we want the contents of the input field to be stored in the database. In order to know the format of the data in the database, we need to have a Schema.

For this tutorial, we will need a very simple Schema that has only two fields. I am going to call the field firstName and lastName. The data stored in both fields will be a String.

After connecting to the database in our app.js we need to define our Schema. Here are the lines you need to add to the app.js.
var nameSchema = new mongoose.Schema({   firstName: String,   lastNameName: String });

Once we have built our Schema, we need to create a model from it. I am going to call my model “DataInput”. Here is the line you will add next to create our mode.
var User = mongoose.model("User", nameSchema);

Creating RESTful API

Now that we have a connection to our database, we need to create the mechanism by which data will be added to the database. This is done through our REST API. We will need to create an endpoint that will be used to send data to our server. Once the server receives this data then it will store the data in the database.

An endpoint is a route that our server will be listening to to get data from the browser. We already have one route that we have created already in the application and that is the route that is listening at the endpoint “/” which is the homepage of our application.

HTTP Verbs in a REST API

The communication between the client(the browser) and the server is done through an HTTP verb. The most common HTTP verbs are
GET, PUT, POST, and DELETE.

The following table explains what each HTTP verb does.

HTTP Verb Operation
GET Read
POST Create
PUT Update
DELETE Delete

As you can see from these verbs, they form the basis of CRUD operations that I talked about previously.

Building a CRUD endpoint

If you remember, the form in our index.html file used a post method to call this endpoint. We will now create this endpoint.

In our previous endpoint we used a “GET” http verb to display the index.html file. We are going to do something very similar but instead of using “GET”, we are going to use “POST”. To get started this is what the framework of our endpoint will look like.

app.post("/addname", (req, res) => {
 
});
Express Middleware

To fill out the contents of our endpoint, we want to store the firstName and lastName entered by the user into the database. The values for firstName and lastName are in the body of the request that we send to the server. We want to capture that data, convert it to JSON and store it into the database.

Express.js version 4 removed all middleware. To parse the data in the body we will need to add middleware into our application to provide this functionality. We will be using the body-parser module. We need to install it, so in your terminal window enter the following command.

npm install body-parser --save

Once it is installed, we will need to require this module and configure it. The configuration will allow us to pass the data for firstName and lastName in the body to the server. It can also convert that data into JSON format. This will be handy because we can take this formatted data and save it directly into our database.

To add the body-parser middleware to our application and configure it, we can add the following lines directly after the line that sets our port.

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Saving data to database

Mongoose provides a save function that will take a JSON object and store it in the database. Our body-parser middleware, will convert the user’s input into the JSON format for us.

To save the data into the database, we need to create a new instance of our model that we created early. We will pass into this instance the user’s input. Once we have it then we just need to enter the command “save”.

Mongoose will return a promise on a save to the database. A promise is what is returned when the save to the database completes. This save will either finish successfully or it will fail. A promise provides two methods that will handle both of these scenarios.

If this save to the database was successful it will return to the .then segment of the promise. In this case we want to send text back the user to let them know the data was saved to the database.

If it fails it will return to the .catch segment of the promise. In this case, we want to send text back to the user telling them the data was not saved to the database. It is best practice to also change the statusCode that is returned from the default 200 to a 400. A 400 statusCode signifies that the operation failed.

Now putting all of this together here is what our final endpoint will look like.

app.post("/addname", (req, res) => {
  var myData = new User(req.body);
  myData.save()
    .then(item => {
      res.send("item saved to database");
    })
    .catch(err => {
      res.status(400).send("unable to save to database");
    });
});
Testing our code

Save your code. Go to your terminal and enter the command node app.js to start our server. Open up your browser and navigate to the URL “http://localhost:3000”. You will see our index.html file displayed to you.

Make sure you have mongo running.

Enter your first name and last name in the input fields and then click the “Add Name” button. You should get back text that says the name has been saved to the database like below.

Access to Code

The final version of the code is available in my Github repo. To access the code click here. Thank you for reading !

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Node.js for Beginners

Learn Node.js from Scratch (Step by Step)

Welcome to my course "Node.js for Beginners - Learn Node.js from Scratch". This course will guide you step by step so that you will learn basics and theory of every part. This course contain hands on example so that you can understand coding in Node.js better. If you have no previous knowledge or experience in Node.js, you will like that the course begins with Node.js basics. otherwise if you have few experience in programming in Node.js, this course can help you learn some new information . This course contain hands on practical examples without neglecting theory and basics. Learn to use Node.js like a professional. This comprehensive course will allow to work on the real world as an expert!
What you’ll learn:

  • Basic Of Node
  • Modules
  • NPM In Node
  • Event
  • Email
  • Uploading File
  • Advance Of Node

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.