【问题标题】:yargs takes only the first word of commandline input stringyargs 只接受命令行输入字符串的第一个单词
【发布时间】:2017-12-20 23:01:17
【问题描述】:

我正在开发一个教程中的 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

【问题讨论】:

    标签: node.js yargs


    【解决方案1】:

    您的代码没有问题,这是 Windows 命令行的行为。 执行命令时请使用双“”而不是“”。在第一个空格之后,所有参数在 Windows 上都会丢失。

    所以运行:

    node app.js -a "lombard street"
    

    而不是

    node app.js -a 'lombard street'
    

    【讨论】:

      猜你喜欢
      • 2013-12-25
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 2020-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多