问题
I am working on a node.js commandline weather app from a tutorial, i realized that when I enter a string as input, only the first word is taken, the string is split into an array of words and only the first word is returned
app.js
const yargs = require('yargs');
const geocode = require('./geocode/geocode.js');
const argv = yargs
.options({
a: {
demand: true,//this argument is require
alias: 'address',
describe: 'Address to fetch weather for',
string: true//always parse the address argument as a string
}
})
.help()
.alias('help', 'h')
.argv;
geocode.geocodeAddress(argv.address, (errorMessage, results) => {
if(errorMessage){
console.log(errorMessage);
}else{
console.log(JSON.stringify(results, undefined, 4));
}
});
geocode.js
const request = require('request');
let geocodeAddress = (address, callback)=>{
let encodedAddress = encodeURIComponent(address);
request({
url:`https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}`,
json:true
}, (err, response, body)=>{
if(err){
callback('unable to connect to service');
}else if(body.status === 'ZERO_RESULTS'){
callback('unable to find address');
}else if(body.status === 'OK'){
callback(undefined, {
address: body.results[0].formatted_address,
latitude: body.results[0].geometry.location.lat,
longitude: body.results[0].geometry.location.lng
});
}
});
}
module.exports.geocodeAddress = geocodeAddress;
here is the output when i run the code
回答1:
There is no problem with your code, it is the behaviour of the Windows command line. When you execute the command please use double "" instead of ''. After the first space all arguments will get lost on Windows.
So run:
node app.js -a "lombard street"
instead of
node app.js -a 'lombard street'
来源:https://stackoverflow.com/questions/47915586/yargs-takes-only-the-first-word-of-commandline-input-string