How to create Node.js modules
Node.js is a module can be published to npm package. When you create a new module, create the package.json
file is the first step.
You can use the npm init
command to create the package.json
file. The command line will prompt package.json
field values you need to enter. 名称(name)
And 版本(version)
these two fields is required. You also need to enter the 入口文件字段(main)
field, of course, you can use the default value index.js
. These steps npm learning (e) the use package.json detailed explanation.
If you want (author) field added as author information, you can use the following format (mail and web site are the optional ones): Your Name <[email protected]> (http://example.com)
Created package.json
after file, you create the file entry module. If you use the default file name index.js
.
In this file, add a function as exports
a property of the object. In this way, then require this document, this function in other code can be used.
exports.printMsg = function() { console.log("This is a message from the demo package"); }
Try:
- Will be published to your package npm.
- Create a directory outside your project.
- Then
cd
enter the new directory. - Execute
npm install <package>
commands. - Test.js create a file, require this package, and a method in which a call.
- Execute
node test.js
commands. Whether the output console.log fill in the information?