npm についてまとめてみる

※この記事は現時点での node.js 最新版 v0.6.6 に付属する npm 1.1.0-beta-4 を元にしています。
※間違い等ありましたらご指摘いただけると幸いです。


npm は node.js のパッケージマネージャーですが意外と色々な機能が搭載されています。


「man を読め」とは良く言われますが、結構 ドキュメント を読むだけでも大変でした。


npm で使えるコマンドは以下の通りです。

  • adduser
    • 対話的に username, password, email を登録します。.nvmrc に credential を保存します。後述の npm star する為にはこの登録が必要です。npm config set で username, _password, email をセットしているとデフォルト値として採用される?npm whoami した時に登録したユーザー名が表示されます。
  • bin
    • express や mocha、node-inspector など単体で実行可能なスクリプト格納しているディレクトリ名を表示する。-g: --global で グローバルなフォルダを表示。
  • bugs
    • パッケージ名を指定して実行。バグレポート送信先を表示する。package.json の bugs.url か bugs に直接指定された文字列が無く、repository か repositories(?) の url が github.com なら issues を、それ以外は search.npmjs.org/#/パッケージ名 を開く、osx は open、それ以外は "google-chrome" がデフォルト、npm config set browser lynx としておくと lynx で開く。
  • c
    • config の alias
  • cache
    • add, ls, clean があり、cache フォルダーにパッケージを追加、パッケージのリスト表示、パッケージを削除する。
    • add: tar ボールやフォルダを cache フォルダに追加する
    • ls: cache された特定のパッケージか全てのパッケージを表示する。--depth でツリーのレベルを指定出来る。
    • clean: パッケージ名を指定すると指定されたパッケージの cache をクリア、何もしてせず実行すると cache を全てクリアする
  • completion
    • これ知らなかったけど地味に便利そう。npm コマンドの補完をしてくれる。コマンドラインから以下を実行するだけ
. <(npm completion)
    • シェルを開くたびにコマンドを叩くのもあれなので ~/.bashrc か ~/.zshrc に設定しておくと良いでしょう。
  • config
    • とにかく設定項目がたくさんあるので config を参考にしていただくか npm config edit していただくと、デフォルトでは vi (Windows では notepad)で現在の設定値及びデフォルト設定値の一覧が表示されるのでそちらを参考に編集していただくと良いかと思います。
    • ちなみに @hakobera さんに教えていただいた npm install 時のオプション -d も config に記述があります。--loglevel info ですね。
    • 設定値は npm/lib/utils/config-defs.js at master · isaacs/npm · GitHub にまとまっている様です。
  • deprecate
    • npm のパッケージオーナー向けコマンド。バグフィックス等で特定のバージョン(以下)を廃止する警告を追加する。
  • docs
    • パッケージに含まれる package.json のhomepage、repository または repositories の url (ここではなぜか github 決めうちっぽい)の readme、search.npmjs.org/#/パッケージ名 の順で開く url を採用する。browser の設定は bugs と同様。
  • edit

パッケージ名を指定して実行。パッケージディレクトリをデフォルトのエディタで表示する。(手元に Windows 環境が無いんですが、notepad でディレクトリ表示ってどうなるんだろう?)

  • explore

パッケージ名を指定して実行。サブシェルでパッケージディレクトリに移動する。-- <コマンド> を指定するとサブシェルでコマンドを実行して戻ってくる。explore の例の様にレポジトリのアップデートを取り込むのに便利そうです。デフォルトは Posix では bash、Windows では cmd なので zsh が好みの方は npm config set shell zsh しておくと良いでしょう。

  • faq
    • npm help faq の alias。
  • find
    • npm search の alias
  • get
    • npm config get の alias
  • help
    • この一連のドキュメント等をコマンドラインから取得可能。トピックが見つからない場合、help-search でドキュメント内を検索する。Posix のデフォルトは man で、Windows は browser、ドキュメントには載っていないがソースを見ると woman というケースがあり、emacs-client を呼んでいるので emacs ユーザーの方は .emacs に (server-start) しておいて npm config set viewer woman しておくと emacs でヘルプトピックが参照出来る。
  • help-search
    • 上記の通り。追加情報を表示する --long をオプションとして指定可能。

オプションなし

$ npm help express   
Top hits for "express"
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
npm help view                                                          express:4
npm help search                                                        express:2
npm help coding-style                                                  express:1
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
(run with -l or --long to see more context)

オプションあり

$ npm help express -l  
npm help view                                                          express:4
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
all of the values from the objects in the list.  For example, to get all
the contributor names for the "express" project, you can do this:
    npm view express contributors.email


npm help search                                                        express:2
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
Search the registry for packages matching the search terms.
If a term starts with `/`, then it's interpreted as a regular expression.
A trailing `/` will be ignored in this case.  (Note that many regular
expression characters must be escaped or quoted in most shells.)


npm help coding-style                                                  express:1
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
 * In front of a leading ( or [ at the start of the line.
  This prevents the expression from being interpreted
  as a function call or property access, respectively.
  • home
    • docs の alias
  • i
    • install の alias
  • info
    • view の alias
  • init
    • これも知らなかったけどちょっと便利。package.json を対話的に作成してくれます。init.author.name, init.author.email, init.author.url, node-version 等は npm config set してあればデフォルト値として使われます。package.json の設定項目もたくさんあるので json を参照していただくか、npm help json して下さい。
  • install
    • こちらはあまり説明の必要は無いかと思います。package.json が含まれたフォルダ、gzipped tarball、gzipped tarball の url からもインストール可能なんですね。オプション類は npm help config して下さい。また依存解決のアルゴリズムについても言及されていますがちょっと難しいのでパスで、、、
  • la, list, ll
    • ls の alias
  • link
    • これはちょっと複雑でよくわかりません。パッケージのディレクトリから link するとグローバルにパッケージの symlink が作成され、この symlink が作成された事で別のディレクトリにあるローカルの node_modules フォルダに symlink を作成する事が可能みたいな機能ですが、あまりユースケースが浮かずイメージ出来ません。
  • ln
    • link の alias
  • outdated
    • パッケージが outdated でないか確認する。
  • owner
    • ls: パッケージを変更出来るユーザーの一覧を表示する。
    • add、rm: パッケージメンテナーを追加、削除する。
  • pack
    • 指定したフォルダ(package.json が必要)をインストール可能な -.tgz の形式で圧縮する。何も指定しない場合カレントフォルダを圧縮する。
  • prefix
    • prefix を表示する。prefix の定義は folders や npm help folders に記述のある通り global は node のインストールディレクトリ、そうでなければカレントパッケージのルートかカレントワーキングディレクトリ。
prefix Configuration

The prefix config defaults to the location where node is installed. On most systems, this is /usr/local, and most of the time is the same as node's process.installPrefix.

On windows, this is the exact location of the node.exe binary. On Unix systems, it's one level up, since node is typically installed at {prefix}/bin/node rather than {prefix}/node.exe.

When the global flag is set, npm installs things into this prefix. When it is not set, it uses the root of the current package, or the current working directory if not in a package already.
  • prune
    • dependencies に含まれないパッケージを削除する。devDependencies で指定されたパッケージを NODE_ENV=production に切り替える際に削除する為?
  • publish
    • package.json の含まれたフォルダか package.json が含まれたフォルダを gzipped tar archive したファイルを npm の package registry に登録する。この操作によって名前でインストールできる様になる。
    • registry については registry か npm help registry を参照して下さい。
  • r, remove, rm, un, unlink
    • uninstall の alias
  • rb
    • rebuild の alias
  • rebuild
    • バージョンアップ時等 C++ アドオンを含むパッケージを recompile する際に実行する。
  • restart
    • package.json の scripts の prerestart, restart, postrestart を実行する。
  • root
    • 効果のある node_modules フォルダ名を表示する。
  • run-script
    • npm run-script パッケージディレクトリ start の様に実行出来る様ですが、あまり直接実行される事を想定されていない模様。
  • s, se
    • search の alias
  • search
    • npm の package registry から指定された条件で検索する。
    • / を検索条件の先頭に指定した場合正規表現で検索する。
$ npm search /'oauth-[a-z]{7}'                                                                                                              
npm http GET https://registry.npmjs.org/-/all/since?stale=update_after&startkey=1324817902000
npm http 200 https://registry.npmjs.org/-/all/since?stale=update_after&startkey=1324817902000
NAME           DESCRIPTION                                                   AUTHOR    DATE              KEYWORDS
oauth-revenge  Sexy OAuth 1.0 Client Module                                  =koba789  2011-12-25 02:56
tweasy         OAuth-enabled Twitter Client with streaming and regular API calls =jchris (prehistoric)
  • set
    • config set の alias
  • show
    • view の alias
  • star
    • お気に入りパッケージに印を付ける。
$ npm view test-tcp
npm http GET https://registry.npmjs.org/test-tcp
npm http 304 https://registry.npmjs.org/test-tcp

{ name: 'test-tcp',
  description: 'testing TCP program, like as perl\'s Test::TCP.',
  'dist-tags': { latest: '0.0.3' },
  versions: [ '0.0.1', '0.0.2', '0.0.3' ],
  maintainers: 'sugyan ',
  time: 
   { '0.0.1': '2011-09-25T15:36:40.641Z',
     '0.0.2': '2011-10-02T07:58:29.695Z',
     '0.0.3': '2011-10-02T08:59:31.060Z' },
  author: 'sugyan  (http://sugyan.com/)',
  repository: 
   { type: 'git',
     url: 'git://github.com/sugyan/node-test-tcp.git' },
  version: '0.0.3',
  engines: { node: '~v0.4.10' },
  dependencies: {},
  devDependencies: { nodeunit: '>=0.5.5' },
  main: 'index',
  keywords: [ 'test', 'tcp' ],
  dist: 
   { shasum: 'ff1803ffc64edeba7cccc92d92badea3b5b15b5e',
     tarball: 'http://registry.npmjs.org/test-tcp/-/test-tcp-0.0.3.tgz' },
  directories: {} }

$ npm star test-tcp
npm http GET https://registry.npmjs.org/test-tcp
npm http 200 https://registry.npmjs.org/test-tcp
npm http PUT https://registry.npmjs.org/test-tcp
npm http 201 https://registry.npmjs.org/test-tcp
★  test-tcp
$ npm view test-tcp
npm http GET https://registry.npmjs.org/test-tcp
npm http 200 https://registry.npmjs.org/test-tcp

{ name: 'test-tcp',
  description: 'testing TCP program, like as perl\'s Test::TCP.',
  'dist-tags': { latest: '0.0.3' },
  versions: [ '0.0.1', '0.0.2', '0.0.3' ],
  maintainers: 'sugyan ',
  time: 
   { '0.0.1': '2011-09-25T15:36:40.641Z',
     '0.0.2': '2011-10-02T07:58:29.695Z',
     '0.0.3': '2011-10-02T08:59:31.060Z' },
  author: 'sugyan  (http://sugyan.com/)',
  repository: 
   { type: 'git',
     url: 'git://github.com/sugyan/node-test-tcp.git' },
  users: { kysnm: true },
  version: '0.0.3',
  engines: { node: '~v0.4.10' },
  dependencies: {},
  devDependencies: { nodeunit: '>=0.5.5' },
  main: 'index',
  keywords: [ 'test', 'tcp' ],
  dist: 
   { shasum: 'ff1803ffc64edeba7cccc92d92badea3b5b15b5e',
     tarball: 'http://registry.npmjs.org/test-tcp/-/test-tcp-0.0.3.tgz' },
  directories: {} }

  • start
  • stop
    • package.json の scripts の prestop, stop, poststop を実行する。
  • submodule
    • git の submodule と同様に作用する。今ひとつユースケースが想定出来ないのでちょっと良くわかりません。
  • tag
    • パッケージの特定のバージョンに特定のタグをつける。latest もタグの1つの様なので stable の様なタグをつける為?
  • test
    • package.json の scripts の pretest, test, posttest を実行する。
  • uninstall
    • パッケージをアンインストールする。
  • unpublish
    • npm の package registry から特定のバージョンまたは全てのバージョンを削除する。ドキュメントには依存モジュールがあるかもしれないので deprecate を代わりに使うべきとの警告が書かれている。
  • unstar
    • ドキュメントでは star と同じと書かれているが star したものは unstar しないと削除されなかった。
  • up
    • update の alias
  • update
    • デフォルトでは全てのパッケージを最新にアップデートする。(パッケージ単体でのアップデートも可能)。tag オプションで latest 以外も指定可能との事だが latest 以外のタグってあるのだろうか?
  • version
    • package.json のバージョンを新しいバージョン番号に書き換える。
    • バージョン番号のルールは semver か npm help semver を参照して下さい。
$ mkdir hoge                                                                                                                                 [62/1805]
$ cd hoge/
$ npm init
Package name: (hoge) 
Description: hogehoge
Package version: (0.0.0) 
Project homepage: (none) 
Project git repository: (none) 
Author name: kysnm
Author email: (none)     
Author url: (none) 
Main module/entry point: (none) 
Test command: (none) 
What versions of node does it run on? (~0.6.6) 
About to write to /Users/jps/work/node/hoge/package.json

{
  "author": "kysnm",
  "name": "hoge",
  "description": "hogehoge",
  "version": "0.0.0",
  "repository": {
    "url": ""
  },
  "engines": {
    "node": "~0.6.6"
  },
  "dependencies": {},
  "devDependencies": {}
}



Is this ok? (yes)  
$ npm version 0.0.1 -m 'version increment'
$ cat package.json                                                                                                                               
{
  "author": "kysnm",
  "name": "hoge",
  "description": "hogehoge",
  "version": "0.0.1",
  "repository": {
    "url": ""
  },
  "engines": {
    "node": "~0.6.6"
  },
  "dependencies": {},
  "devDependencies": {}
}%                             
  • view
    • npm の package registry から指定されたパッケージの情報を表示する。
    • 様々な検索条件を指定出来るので view か npm help view を参照して下さい。
  • whoami
    • 登録された username を表示する。
  • apihelp
    • 上記のコマンド類をスクリプト内で利用する際の API ドキュメントを表示する。
    • npm apihelp bin 等。


いやー、本当にたくさん機能がありますね。これを書いている途中で操作をミスって一部消してしまうというトラブルがあり泣きそうになりましたw


調べていて面白かったのは package.json の typo に結構対応している事です。
以下の様に定義されています。

  // http://registry.npmjs.org/-/fields
  var typos = { "dependancies": "dependencies"
              , "dependecies": "dependencies"
              , "depdenencies": "dependencies"
              , "devEependencies": "devDependencies"
              , "depends": "dependencies"
              , "devDependences": "devDependencies"
              , "devDepenencies": "devDependencies"
              , "devdependencies": "devDependencies"
              , "repostitory": "repository"
              , "prefereGlobal": "preferGlobal"
              , "hompage": "homepage"
              , "hampage": "homepage" // XXX maybe not a typo, just delicious?
              , "autohr": "author"
              , "autor": "author"
              , "contributers": "contributors"
              , "publicationConfig": "publishConfig"
              }

<*snip*>

  // bugs typos
  var bugsTypos = { "web": "url"
                  , "name": "url"
                  }

<*snip*>
    
    // script typos
  var scriptTypos = { "server": "start" }


これを調べるきっかけを与えてくれた @sugyan さん、node 塾でソースコードリーディングに慣れさせていただいた @hakobera さんに感謝します。ありがとうございました。