Home » Node.js30 July 2017

Node.js: Packaging your Node.js Module/Project

This article shows how you can package your Node.js module or project using npm init command. Running this command will create a package.json file which contains all the necessary packaging information.

Here’s a step-by-step guide to create package file with npm init command.

1) Open terminal/command-prompt
2) Go to your Node.js module/project directory. In my case, the directory is /var/www/html/test/nodejs/myapp.

3) Run npm init command. This will ask certain questions which you have to answer.

It asks for your module name, description, version, author, etc. It also provides the default value within small brackets. If you can to keep the default suggested value then you can simply press Enter. Like, I just pressed enter without typing anything for name, version, entry point and license. If you have Git repository for your module then you can type the repository link when it asks for git repository. Otherwise, you can just skip it by pressing Enter.

4) Your module’s package.json file has been created in your module’s folder. Here’s the file content:

5) As seen in the package.json file, the main file or the first file to load for this module is index.js. So, we have to create a new file named index.js in our module’s folder.

6) A module can be dependent on other modules. If our module is dependent on other modules then we need to specify dependencies in our module’s package.json file.

Suppose, we are using Express Web Framework in our Node.js project/module. For this, we need to install the express module. So, we can use the following command to install express module. Note the -save option at the end of the command. This will automatically add the installed module dependency in the project.json file.

7) After you install express module, a new directory named node-modules is created inside your project/module’s directory. This directory contains all the third-party node module you install. So, it will now contains express module and all the other module that express module is dependent on.

8) Your module’s package.json file is also updated. Here’s the updated file content:

As you can see that the dependency of express module has been added to package.json file.

9) Now, while shipping the module or installing the module in another machine, you don’t need to copy the node-modules folder of your project. You can just copy the index.js and other js files and the package.json file and run npm install command. This will automatically install the express module because it’s listed as dependency for your module.

Hope this helps. Thanks.


Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed