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 :-
- Outside your code, start your command line / terminal emulator and change directory to where your application code is located eg. /myCode.
- 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)
- 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.
- We can now create a Const variable in our code to require lodash
const _ = require(‘lodash’);
- 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 😉