Creating Node.js modules
See Details
Table of contents
Node.js modules are a type ofpackage that can be published to npm.
Overview
- Create a
package.jsonfile - Create the file that will be loaded when your module is required by another application
- Test your module
Create apackage.json file
- To create a
package.jsonfile, on the command line, in the root directory of your Node.js module, runnpm init:- Forscoped modules, run
npm init --scope=@scope-name - Forunscoped modules, run
npm init
- Forscoped modules, run
- Provide responses for the required fields (
nameandversion), as well as themainfield:name: The name of your module.version: The initial module version. We recommend followingsemantic versioning guidelines and starting with1.0.0.
For more information onpackage.json files, see "Creating a package.json file".
Create the file that will be loaded when your module is required by another application
Create a file with the same name you provided in themain field. In that file, add a function as a property of theexports object. This will make the function available to other code:
exports.printMsg=function(){console.log("This is a message from the demo package");}
Test your module
Publish your package to npm:
- Forprivate packages andunscoped packages, use
npm publish. - Forscoped public packages, use
npm publish --access public
- Forprivate packages andunscoped packages, use
On the command line, create a new test directory outside of your project directory.
mkdir test-directorySwitch to the new directory:
cd /path/to/test-directoryIn the test directory, install your module:
npm install <your-module-name>In the test directory, create a
test.jsfile which requires your module and calls your module as a method.On the command line, run
node test.js. The message sent to the console.log should appear.
![dependabot[bot]](/image.pl?url=https%3a%2f%2fgithub.com%2fdependabot%5bbot%5d.png%3fsize%3d40&f=jpg&w=240)


