yargs仅采用命令行输入字符串的第一个单词 [英] yargs takes only the first word of commandline input string

查看:67
本文介绍了yargs仅采用命令行输入字符串的第一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从一个教程中开发一个node.js命令行天气应用程序,我意识到当我输入一个字符串作为输入时,只有第一个单词被使用,该字符串被分成单词数组,只有第一个单词返回

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

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;

这是我运行代码时的输出

推荐答案

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

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.

所以运行:

node app.js -a "lombard street"

代替

node app.js -a 'lombard street'

这篇关于yargs仅采用命令行输入字符串的第一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆