如何从npm脚本中获取对象参数(NodeJS + TypeScript)

lc8prwob  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(180)

我想通过NPM脚本传递一个对象,如

"update-user-roles": "ts-node user-roles.ts {PAID_USER: true, VIP: true}"

我的函数拾取了对象,但不断添加额外的逗号,所以它没有正确地更新用户。如何按原样接收对象?

async function updateUserRoles(roles: any) {
    const userID = await getAuth().then((res) => res.uid);
    updateUser({
        userID: userID,
        fields: {
            roles: {
                roles
            },
        }
    })
    console.log(`User roles successfully added: ${roles}`)
}

const rolesString = JSON.stringify(process.argv.slice(2))
updateUserRoles(JSON.parse(rolesString))

我收到以下消息:

User roles successfully added: {PAID_USER:,true,,VIP:,true}
0dxa2lsx

0dxa2lsx1#

你得到逗号,的原因是因为Nodejs会在空白处分割命令行参数。process.argv数组如下所示:

[
  '/home/lindu/workspace/project/node_modules/.bin/ts-node',
  '/home/lindu/workspace/project/index.ts',
  '{PAID_USER:',
  'true,',
  'VIP:',
  'true}'
]

process.argv属性返回一个数组,其中包含启动Node.js进程时传递的命令行参数。

选项1.传入JSON字符串

$ npx ts-node ./index.ts '{"PAID_USER": true, "VIP": true}'

index.ts

console.log(process.argv);
console.log(JSON.parse(process.argv.slice(2)[0]));

输出:

[
  '/home/lindu/workspace/project/node_modules/.bin/ts-node',
  '/home/lindu/workspace/project/index.ts',
  '{"PAID_USER": true, "VIP": true}'
]
{ PAID_USER: true, VIP: true }

选项2.传入字符串,解析为JSON字符串。

npx ts-node ./index.ts '{PAID_USER: true, VIP: true}'

index.ts

console.log(process.argv);

const arg = process.argv.slice(2)[0];
const obj = JSON.parse(JSON.stringify(eval('(' + arg + ')')));
console.log(obj, typeof obj, obj.PAID_USER, obj.VIP);

输出:

[
  '/home/lindu/workspace/project/node_modules/.bin/ts-node',
  '/home/lindu/workspace/project/index.ts',
  '{PAID_USER: true, VIP: true}'
]
{ PAID_USER: true, VIP: true } object true true

选项3,使用minimistjs包。

相关问题