yargs 只接受命令行输入字符串的第一个单词
yargs takes only the first word of commandline input string
我正在开发教程中的 node.js 命令行天气应用程序,我意识到当我输入一个字符串作为输入时,只采用第一个单词,该字符串被拆分成一个单词数组,只返回第一个单词
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
你的代码没有问题,是Windows命令行的行为。
执行命令时请使用双“”而不是''。在第一个 space 之后,所有参数都将在 Windows 上丢失。
所以运行:
node app.js -a "lombard street"
而不是
node app.js -a 'lombard street'
我正在开发教程中的 node.js 命令行天气应用程序,我意识到当我输入一个字符串作为输入时,只采用第一个单词,该字符串被拆分成一个单词数组,只返回第一个单词
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
你的代码没有问题,是Windows命令行的行为。 执行命令时请使用双“”而不是''。在第一个 space 之后,所有参数都将在 Windows 上丢失。
所以运行:
node app.js -a "lombard street"
而不是
node app.js -a 'lombard street'