LoginSignup
0
0

More than 3 years have passed since last update.

npm token createの結果をjsonで取得する

Last updated at Posted at 2020-08-13

TL; DR

npm token create --json

経緯

記事のタイトルとは関係ないけど、Node.jsのプログラム中からnpmアカウントのAuth Tokenを生成する方法で困ってた。

ここにあるnpm token create以外にAPIが見つからないけど、npm token createはCLI上でインタラクティブにパスワードの入力を求めてくる。

これについては下記の方法で可能だということがわかった。
意外とお手軽で良かった。

main.js
const child = require('child_process')
child.spawn("npm", ["token", "create"], { stdio: 'inherit' })

ということで実行してみたところ、パスワードも問題なく親プロセスから対話的に入力でき、トークンが生成できた。(トークン部分は隠してあります)

node main.js

npm password: 
┌────────────────┬──────────────────────────────────────┐
│ token          │ xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx │
├────────────────┼──────────────────────────────────────┤
│ cidr_whitelist │                                      │
├────────────────┼──────────────────────────────────────┤
│ readonly       │ false                                │
├────────────────┼──────────────────────────────────────┤
│ created        │ 2020-08-13T07:53:39.394Z             │
└────────────────┴──────────────────────────────────────┘

しかし実際にはこのトークンをは次の処理への入力にする必要があり、(これパースするのか・・・面倒だな・・・)と思って、ダメ元で--jsonオプションを渡してみたらJSONで取得できた。
感謝感謝。

main.js
const child = require('child_process')
child.spawn("npm", ["token", "create", "--json"], { stdio: 'inherit' })
node main.js 

npm password: 
{"token":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx","cidr_whitelist":[],"readonly":false,"created":"2020-08-13T08:04:16.531Z"}

これならあとはstdoutへの出力を親プロセスで受け取るだけなのでいけそう。


(2020.08.14追記)
あとは簡単だと思ってたらめちゃくちゃ時間を食った上、腹落ちしない結果になったことを報告します。
https://qiita.com/nariakiiwatani/items/0ef81f31ca9d1d071076

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0