在调用函数时使用process.argv [2]的意义

时间:2019-02-25 13:44:40

标签: node.js

我是Node.js的新手,而我所遵循的教程总是最终使用JSONconvert(process.argv[2],process.argv[3])调用函数,或者有时甚至使用JSONconvert(process.argv[2])调用函数。我的问题是process.arv[2]的用途是什么,因为即使我在没有代码的情况下运行代码,它仍然可以工作。如果我执行console.log,它将打印未定义。作为参考,这里是我正在使用的.js代码,它将CSV转换为JSON。

const fs= require('fs');
const path=require('path');
const csv=require("csvtojson");
const csvFilePath = path.join(__dirname, 'customer-data.csv')
const jsonFilePath = path.join(__dirname, 'customer-data.json') 

const JSONconvert = () => {
    console.log('Converting from CSV file to JSON file ...')

    const converter = csv().fromFile(csvFilePath)

    converter.then((jsonObj) => {
        fs.writeFileSync(jsonFilePath, JSON.stringify(jsonObj, null, 2))
    })

    converter.on('error', (error) => {
        console.log(`error: ${error}`)
        process.exit(1)
    })

    converter.on('done', () => {
        console.log('Successfully converted at', jsonFilePath)
    })
}

JSONconvert(process.argv[2],process.argv[3]);

1 个答案:

答案 0 :(得分:-1)

用于调用节点脚本的完整命令行为node script arg1 arg2 ...。这些元素保存在数组process.argv中。元素0始终是节点,元素1始终是您的脚本名称,之后的所有内容都是命令行中提供的参数。如果您不提供,则它们将是不确定的。

有关更多信息: