3.4 Using npm Modules

  1. Check the version of your npm by typing npm -v in your terminal. No matter what number you get, what is important is you have npm installed.
  2. When you are in your project folder, run npm init. It prompts several questions about your npm project you need to answer. Just do the same as shown below. It is for creating a npm file.
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (notes-node)
version: (1.0.0)
description:
entry point: (app.js)
test command:
git repository:
keywords:
author: Jude
license: (ISC)
About to write to C:\Users\GaoJu\OneDrive - University of Waterloo\CURRENT\notes-node\package.json:
{
"name": "notes-node",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Jude",
"license": "ISC"
}
Is this OK? (yes)
  1. The package we will require is called lodash. Go to the website: https://lodash.com/
  2. We are going to install lodash now. npm install lodash --save. The --save flag will update the npm JSON file you created after asked those questions just now. We can verify the flag is working by opening the package.json. In dependencies, we see "lodash": "^4.17.10".
  3. Require lodash. const _ = require('lodash');
  4. Looking at documentation, use lodash. In particular, we take _.isString() as an example here. We test this function by
console.log(_.isString(true));
console.log(_.isString('Jude'));

Running app.js, we get the following output

$ node app.js
starting app...
Sarting notes.js
false
true

Apparently, the function _.isString() is working perfectly. This is an example of using a third-party module.

  1. Now, we start to use another function from lodash: _.uniq(). This method takes an array and returns another array with distinct elements. Here is how we use the function:
var filteredArray = _.uniq(['Jude', 'Jude', 1, 1, 2, 'Jude', 1, 1]);
console.log(filteredArray);

We get the output: [ 'Jude', 1, 2 ].

  1. The last thing is about the folder node_modules. This folder contains the generated code from npm. We should NOT modify this folder. We have seen that e.g. lodash is included in our package.json file. When you send your code to your friend, you should NOT include node_modules folder, since they sometimes can get really large. As long as you include “package.json”, your friend could run npm install in the project folder to make node_modules on their own. Doing this increases the speed of transition and saves time.