以函数调用的方式使用npm cli的命令。
- 以函数调用的方式执行npm cli command
- 提供legacy和sso两种登录API
- 在函数调用时指定登录凭证,避免不同用户之间互相影响
npm i npm-command-call
根据使用场景在下面三种方式中选择一种:
方式 | 使用场景 |
---|---|
1、authentication token | 运行时使用一个账户,静态指定 |
2、使用登录API和默认的登录态管理 | 运行时使用一个账户,动态指定 |
3、使用登录API并自己管理登录态 | 运行时并发使用多个账户,动态指定 |
引入API并调用。
const npmCmdCall = require('npm-command-call')
npmCmdCall.runCmd(['whoami']).catch((err) => {
console.log(err)
})
import * as npmCmdCall from('npm-command-call')
npmCmdCall.runCmdWithCreds(['whoami'], {
token: '3fd34677-e7a6-4e21-9d84-******'
}).catch((err) => {
console.log(err)
})
对于前两种登录方式,使用runCmd
;对于最后一种登录方式,使用runCmdWithCreds
。
使用密码进行登录
userInfo
指用户信息,属性包括username
,password
,email
,必填;registry
指npm-registry,选填;scope
指npm-scope,选填;self
指是否要自己处理登录态,默认为false,选填。
adduserByLeagcy({
username: 'u******',
password: 'p******',
email: 'e******'
}).catch((err) => {
console.log(err)
})
使用SSO进行登录
registry
指npm-registry,选填;scope
指npm-scope,选填;cb
指处理sso链接的函数,默认打开浏览器并访问该链接,选填;ssoType
指处理sso的类型,取值包括’oauth‘和’saml‘,默认为’oauth‘,选填;self
指是否要自己处理登录态,默认为false,选填。
adduserBySso('https://registry.npmjs.org', undefined, (ssoUrl)) => {
openUrl(ssoUrl)) // 以某种形式展示ssoUrl,使得用户可以访问
}, 'oauth', true).then(({ token }) => {
save({ token }) // 以某种形式保存登录态
}).catch((err) => {
console.log(err)
})
运行命令
argvArr
指命令行参数,必填。
runCommand(['whoami', '--registry=https://registry.npmjs.org']).catch((err) => {
console.log(err)
})
指定登录态运行命令
argvArr
指命令行参数,必填;creds
指用户凭证,属性包括token
,必填;registry
指npm-registry,选填;
runCmdWithCreds(["publish", ".", "--tag=beta"], {
token: '3fd34677-e7a6-4e21-9d84-******'
}).catch((err) => {
console.log(err)
})
使用SSO进行登录,返回token和sso链接,返回的token需要等点击sso链接进行登录后才会生效。
registry
指npm-registry,选填;scope
指npm-scope,选填;ssoType
指处理sso的类型,取值包括’oauth‘和’saml‘,默认为’oauth‘,选填;
adduserBySsoUnsafe('https://registry.npmjs.org').then(({ token, sso }) => {
openUrl(sso) // 在浏览器上打开链接进行登录
save({ token }) // 以某种形式保存登录态
}).catch((err) => {
console.log(err)
})
检测token是否生效,结合adduserBySsoUnsafe
使用。
token
指adduserBySsoUnsafe
返回的授权令牌,必填;registry
指npm-registry,选填;scope
指npm-scope,选填;
adduserBySsoUnsafe('https://registry.npmjs.org')
.then(({ token, sso }) => {
openUrl(sso) // 在浏览器上打开链接进行登录
return checkSsoToken(token, 'https://registry.npmjs.org',)
}).catch((err) => {
console.log(err)
})