首页 > 语言 > JavaScript > 正文

详解Node.js 命令行程序开发教程

2024-05-06 15:16:12
字体:
来源:转载
供稿:网友

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

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

下面就是我在它的基础上扩展的教程,应该是目前最好的解决方案了。

一、可执行脚本

我们从最简单的讲起。

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

#!/usr/bin/env nodeconsole.log('hello world');

然后,修改 hello 的权限。

$ chmod 755 hello

现在,hello 就可以执行了。

$ ./hellohello world

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

{ "name": "hello", "bin": {  "hello": "hello" }}

然后执行 npm link 命令。

$ npm link

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

$ hellohello world

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

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

下面是一个脚本 hello 。

#!/usr/bin/env nodeconsole.log('hello ', process.argv[2]);

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

$ ./hello tomhello tom

上面代码中,实际上执行的是 node ./hello tom ,对应的 process.argv 是 ['node', '/path/to/hello', 'tom'] 。

三、新建进程

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

#!/usr/bin/env nodevar name = process.argv[2];var exec = require('child_process').exec;var child = exec('echo hello ' + name, function(err, stdout, stderr) { if (err) throw err; console.log(stdout);});

用法如下。

$ ./hello tomhello tom

四、shelljs 模块

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

npm install --save shelljs

然后,改写脚本。

#!/usr/bin/env nodevar name = process.argv[2];var shell = require("shelljs");shell.exec("echo hello " + name);

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

require('shelljs/global');if (!which('git')) { echo('Sorry, this script requires git'); 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 commit -am "Auto-commit"').code !== 0) { echo('Error: Git commit failed'); exit(1);}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选