Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

shell.js与yargs命令行开发 #48

Open
youngwind opened this issue Mar 21, 2016 · 0 comments
Open

shell.js与yargs命令行开发 #48

youngwind opened this issue Mar 21, 2016 · 0 comments

Comments

@youngwind
Copy link
Owner

与终端的交互

一种编程语言是否易用,很大程度上,取决于开发命令行程序的能力。
忽然想搞明白平常用的那些npm包,它们是如何接受参数然后运行的。
#1. shell.js

关于nodejs如何调用shell进程,可以参考 #46 #47 ,里面介绍了两种方法。下面主要说一下shell.js一些比较方便但是不常用的方法。

  1. 检查某个文件夹是否存在
shell.test('-d','path');  // 当path为目录,返回true
shell.test('-e','path');  // 当path为目录或者文件,返回true
  1. 重写文件内容
"string".to('file');
  1. 添加文件内容到尾部
"string".toEnd('file');
  1. 从文件中读取字符串然后进行正则匹配替换
shell.sed(/a/g,'b','test.js');  // 把test.js里面的所有字母b替换成字母a然后返回
shell.sed('-i',/a/g,'b','test.js');  //替换之后重新写入覆盖源文件

#2. yargs

yargs可以将命令行的参数转化成对象,比如我有一个test.js文件

var argv = require('yargs').argv;
console.log(argv)

当我执行

node test.js --name lsf --emai 123@qq.com

终端输出

{ _: [], name: 'a', email: 'b', '$0': 'test.js' }

所有argv就可以很方便地提取到argv.name和argv.email.
如果是用process.argv去获取的话,是这样的

[ '/usr/local/bin/node',
  '/Users/youngwind/www/lazy-smart/test.js',
  '--name',
  'a',
  '--email',
  'b' ]

一点都不友好。

@youngwind youngwind changed the title shell.js与yargs二三事 shell.js与yargs命令行开发 Mar 21, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant