Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Node.js By Example
  • Table Of Contents Toc
Node.js By Example

Node.js By Example

By : Krasimir Tsonev
3.5 (2)
close
close
Node.js By Example

Node.js By Example

3.5 (2)
By: Krasimir Tsonev

Overview of this book

If you are a JavaScript developer with no experience with Node.js or server-side web development, this book is for you. It will lead you through creating a fairly complex social network. You will learn how to work with a database and create real-time communication channels.
Table of Contents (13 chapters)
close
close
12
Index

Managing and distributing packages

Once we understand the idea of require and exports, we should start thinking about grouping our logic into building blocks. In the Node.js world, these blocks are called modules (or packages). One of the reasons behind the popularity of Node.js is its package management.

Node.js normally comes with two executables—node and npm. NPM is a command-line tool that downloads and uploads Node.js packages. The official site, https://npmjs.org/, acts as a central registry. When we create a package via the npm command, we store it there so that every other developer may use it.

Creating a module

Every module should live in its own directory, which also contains a metadata file called package.json. In this file, we have set at least two properties—name and version:

{
   "name": "my-awesome-nodejs-module",
   "version": "0.0.1"
}

We can place whatever code we like in the same directory. Once we publish the module to the NPM registry and someone installs it, he/she will get the same files. For example, let's add an index.js file so that we have two files in the package:

// index.js
console.log('Hello, this is my awesome Node.js module!');

Our module does only one thing—it displays a simple message to the console. Now, to upload the modules, we need to navigate to the directory containing the package.json file and execute npm publish. This is the result that we should see:

Creating a module

We are ready. Now our little module is listed in the Node.js package manager's site and everyone is able to download it.

Using modules

In general, there are three ways to use the modules that are already created. All three ways involve the package manager:

  • We may install a specific module manually. Let's say that we have a folder called project. We open the folder and run the following:
    npm install my-awesome-nodejs-module
    

    The manager automatically downloads the latest version of the module and puts it in a folder called node_modules. If we want to use it, we do not need to reference the exact path. By default, Node.js checks the node_modules folder before requiring something. So, just require('my-awesome-nodejs-module') will be enough.

  • The installation of modules globally is a common practice, especially if we talk about command-line tools made with Node.js. It has become an easy-to-use technology to develop such tools. The little module that we created is not made as a command-line program, but we can still install it globally by running the following code:
    npm install my-awesome-nodejs-module -g
    

    Note the -g flag at the end. This is how we tell the manager that we want this module to be a global one. When the process finishes, we do not have a node_modules directory. The my-awesome-nodejs-module folder is stored in another place on our system. To be able to use it, we have to add another property to package.json, but we'll talk more about this in the next section.

  • The resolving of dependencies is one of the key features of the package manager of Node.js. Every module can have as many dependencies as you want. These dependences are nothing but other Node.js modules that were uploaded to the registry. All we have to do is list the needed packages in the package.json file:
    {
        "name": "another-module", 
        "version": "0.0.1", 
        "dependencies": {
            "my-awesome-nodejs-module": "0.0.1"   
        }
    }

    Now we don't have to specify the module explicitly and we can simply execute npm install to install our dependencies. The manager reads the package.json file and saves our module again in the node_modules directory. It is good to use this technique because we may add several dependencies and install them at once. It also makes our module transferable and self-documented. There is no need to explain to other programmers what our module is made up of.

Updating our module

Let's transform our module into a command-line tool. Once we do this, users will have a my-awesome-nodejs-module command available in their terminals. There are two changes in the package.json file that we have to make:

{
   "name": "my-awesome-nodejs-module",
   "version": "0.0.2",
   "bin": "index.js"
}

A new bin property is added. It points to the entry point of our application. We have a really simple example and only one file—index.js.

The other change that we have to make is to update the version property. In Node.js, the version of the module plays important role. If we look back, we will see that while describing dependencies in the package.json file, we pointed out the exact version. This ensures that in the future, we will get the same module with the same APIs. Every number from the version property means something. The package manager uses Semantic Versioning 2.0.0 (http://semver.org/). Its format is MAJOR.MINOR.PATCH. So, we as developers should increment the following:

  • MAJOR number if we make incompatible API changes
  • MINOR number if we add new functions/features in a backwards-compatible manner
  • PATCH number if we have bug fixes

Sometimes, we may see a version like 2.12.*. This means that the developer is interested in using the exact MAJOR and MINOR version, but he/she agrees that there may be bug fixes in the future. It's also possible to use values like >=1.2.7 to match any equal-or-greater version, for example, 1.2.7, 1.2.8, or 2.5.3.

We updated our package.json file. The next step is to send the changes to the registry. This could be done again with npm publish in the directory that holds the JSON file. The result will be similar. We will see the new 0.0.2 version number on the screen:

Updating our module

Just after this, we may run npm install my-awesome-nodejs-module -g and the new version of the module will be installed on our machine. The difference is that now we have the my-awesome-nodejs-module command available and if you run it, it displays the message written in the index.js file:

Updating our module
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Node.js By Example
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon