Reputation: 5914
I am very new to using the NodeJS CLI command of process.argv
to be able to pass a variable containing an object to my function method, but it seems that the property values within my object are not being found when this process is called. I am receiving an error at the second property of my object siteUrl
and can't seem to figure out if it is the way that process.argv
compiles information or if I am using the command incorrectly. If I replace process.argv
with params
then I do not receive errors.
Here is my terminal command:
node app.js params
Here is my variable setup:
var siteUrl = encodeURIComponent('http://www.test.com/');
var params = {
auth: auth,
siteUrl: siteUrl,
resource: {
'startDate': moment().subtract(3, 'days').format("YYYY-MM-DD"),
'endDate': moment().subtract(2, 'days').format("YYYY-MM-DD"),
'dimensions': ['query', 'page'],
'dimensionFilterGroups': [{
'filters': [{
'dimension': 'country',
'operator': 'equals',
'expression': 'USA'
}]
}]
}
Here is my method
var query = webmasters.searchanalytics.query(process.argv, function(err, res){
var formattedQueryList = [];
if (err){
console.log('This is the error: ' + err);
} else { ... }
I'm also logging my object to make sure values are present:
console.log(params.resource.startDate)
console.log(params.resource.startDate)
console.log(params.resource.endDate)
console.log(params.siteUrl)
console.log(siteUrl)
here is the console.log:
2017-02-11
2017-02-12
http%3A%2F%2Fwww.test.com%2F
http%3A%2F%2Fwww.test.com%2F
This is the error: Error: Missing required parameters: siteUrl
Upvotes: 2
Views: 2260
Reputation: 136
process.argv
is a list of the parameters you append to the terminal command.
In your case, process.argv[2]
would be the string params
, and not the actual variable value. You either need to pass the JSON itself (with proper escaping) via the CLI, then parse it with JSON.parse
, or manually check the value of process.argv[2]
.
Upvotes: 0
Reputation: 5292
When you pass an argument node treat it as string. So you have to take care of the Json formating.
e.g.
You want to pass an object person, here you can explicitly set the \".
node lib/index.js {\"name\":\"Bob\"}
Or in a different way with ' wrapping the json:
node lib/index.js '{"name":"Bob"}'
And in your code, you should parse the string as a JSON.
const obj = JSON.parse( process.argv[2] );
console.log(obj);
console.log('Hello ' + obj.name);
which will give you Hello Bob
. In your case you maybe can use JSON.stringify(params)
before you pass it as argument.
Hope this help to clarify.
Upvotes: 2