Node.js之NPM模块开发

NPM的全称是Node Package Manager,是一个NodeJS包管理和分发工具,已经成为了非官方的发布Node模块(包)的标准。

创建目录

1
2
mkdir first_module
cd first_module

初始化

1
npm init

实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
fujinliang:first_module fujinliang$ npm init
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> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (first_module)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/fujinliang/StudyNotes/Node/first_module/package.json:

{
"name": "first_module",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}


Is this ok? (yes) yes
fujinliang:first_module fujinliang$

发布到NPM

注册用户

https://www.npmjs.com,注册账号

为项目添加用户

1
npm adduser

实例:

1
2
3
4
fujinliang:first_module fujinliang$ npm adduser
Username: fujinliang
Password:
Email: (this IS public) 719143226@qq.com

查询用户

1
npm whoami

发布

1
npm publish

出现403的错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
npm ERR! publish Failed PUT 403
npm ERR! Darwin 15.6.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "publish"
npm ERR! node v6.10.1
npm ERR! npm v3.10.10
npm ERR! code E403

npm ERR! you do not have permission to publish "first_module". Are you logged in as the correct user? : first_module
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR! /Users/fujinliang/StudyNotes/Node/first_module/npm-debug.log

解决方法:出现403,可能是你的模块已经被别人注册,修改自己package.json的name就可以了

1
2
3
4
5
6
7
8
9
10
11
{
"name": "first_module_01",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}

发布成功

1
2
fujinliang:first_module fujinliang$  npm publish
+ first_module_01@1.0.0
谢谢你请我吃糖果