Using 3rd Party Packages In Node.js


One of the most profound capabilities of any modern programming language is it’s ability to consume / use 3rd party packages that add functionality and make coding easier and more powerful. The Node.js language has npm which claims to be the world’s largest Javascript repository of reusable code.

In this post I’m going to summarise how packages from npm can be used in your own code…

Firstly, I will assume that you have both Node.js and npm installed, and that you are starting to code your application / solution, and have searched through npm and found the package you need – the one I use frequently is lodash which provides a wide range of methods for working with arrays, strings, numbers, dates, objects etc.

To use lodash :-

  1. Outside your code, start your command line / terminal emulator and change directory to where your application code is located eg. /myCode.
  2. Initialise npm in the /myCode directory using the command npm init this will prompt a few questions .. and will create a new file packages.json which will use used to store details of the dependances (the packages you install / use)
  3. Now we can install the lodash module ..   use the command npm install lodash —save    (the —save flag updates packages.json with details of the lodash package, also a “node-modules” folder will be created in /myCode which will be used to store local copy of the npm packages you install – in this case lodash.
    Each time a new npm package is installed, the packages.json file is updated with a dependancy.
  4. We can now create a Const variable in our code to require lodash

    const _ = require(‘lodash’);

  5. That’s it !   We can now use modules of lodash in our code.

As an emaple of now using one of the methods from lodash, we could test if the value we pass in a variable is actually a number using the method _.isNumber :-

console.log(_.isNumber(23); Would be true

console.og(_.isNumber(‘David’); Would be false

Thanks for reading this – please provide comments if you need to raech out to me 😉

Comments are closed.

Website Powered by WordPress.com.

Up ↑

%d bloggers like this: