Nodejs命令行程序开发教程

一种编程语言是否易用,很大程度上,取决于开发命令行程序的能力。

Node.js作为目前最热门的开发工具之一,怎样使用它开发命令行程序,是Web开发者应该掌握的技能。

最近,Npm的网志有一组系列文章,我觉得写得非常好。下面就是我在它的基础上扩展的教程,应该是目前最好的解决方案了。

一、可执行脚本

我们从最简单的讲起。

首先,使用JavaScript语言,写一个可执行脚本hello。

#!/usr/bin/envnode

console.log(helloworld);

然后,修改hello的权限。

$chmodhello

现在,hello就可以执行了。

$./hello

helloworld

如果想把hello前面的路径去除,可以将hello的路径加入环境变量PATH。但是,另一种更好的做法,是在当前目录下新建package.json,写入下面的内容。

{

name:hello,

bin:{

hello:hello

}

}

然后执行npmlink命令。

$npmlink

现在再执行hello,就不用输入路径了。

$hello

helloworld

二、命令行参数的原始写法

命令行参数可以用系统变量process.argv获取。

#!/usr/bin/envnode

console.log(hello,process.argv[2]);

执行时,直接在脚本文件后面,加上参数即可。

$./hellotom

hellotom

三、新建进程

脚本可以通过child_process模块新建子进程,从而执行Unix系统命令。

#!/usr/bin/envnode

varname=process.argv[2];

varexec=require(child_process).exec;

varchild=exec(echohello+name,function(err,stdout,stderr){

if(err)throwerr;

console.log(stdout);

});

用法如下。

$./hellotom

hellotom

四、shelljs模块

shelljs模块重新包装了child_process,调用系统命令更加方便。它需要安装后使用。

npminstall--saveshelljs

然后,改写脚本。

#!/usr/bin/envnode

varname=process.argv[2];

varshell=require(shelljs);

shell.exec(echohello+name);

上面代码是shelljs的本地模式,即通过exec方法执行shell命令。此外还有全局模式,允许直接在脚本中写shell命令。

require(shelljs/global);

if(!which(git)){

echo(Sorry,thisscriptrequiresgit);

exit(1);

}

mkdir(-p,out/Release);

cp(-R,stuff/*,out/Release);

cd(lib);

ls(*.js).forEach(function(file){

sed(-i,BUILD_VERSION,v0.1.2,file);

sed(-i,/.*REMOVE_THIS_LINE.*\n/,,file);

sed(-i,/.*REPLACE_LINE_WITH_MACRO.*\n/,cat(macro.js),file);

});

cd(..);

if(exec(git







































好的中医白癜风医院
新春惠民中科白癜风优惠



转载请注明:http://www.nylrzx365.com/glgj/7961.html