导航栏: 首页 评论列表

转载:用node.js开发命令行工具

默认分类 2014/11/05 02:57

原文地址:
http://binbinliao.com/programming/commandline-nodejs.html
http://www.hacksparrow.com/commandline-node-js-scripts-utilities-modules.html

用node.js开发命令行工具

2012-10-13

node.js简介

Node让你可以用javascript编写服务器端程序,让javascript脱离web浏览器的限制,像C#、JAVA、Python等语言一样在服务器端运行,这也让一些熟悉Javascript的前端开发人员进军到服务器端开发提供了一个便利的途径。Node是基于Google的V8引擎封装的,并提供了一些编写服务器程序的常用接口,例如文件流的处理。Node的目的是提供一种简单的途径来编写高性能的网络程序。

命令行工具

node.js除了做服务器端程序,其实还可以做很多事情,其中就包括开发命令行工具。本文就介绍一下怎样使用Node来开发命令行工具。

今天需要创建一个显示当前文件夹下的所以文件和文件夹名。

首先创建一个文件夹叫nodefolder,然后新建一个nodefolder.js的文件,代码如下:

var fs = require("fs"),
    path = process.cwd();

fs.readdir(path, function(err, files){
    if(err){
        return console.log(err);
    }
    for(var i = 0; i < files.length; i += 1){
        console.log(files[i]);
    }
});

现在已经可以用node来运行这个js文件了,下面是运行截图:

node 运行结果

已经成功运行了,那接下来我们该怎么办呢,首先需要在文件头部添加一行,如下:

#! /usr/bin/env node
var fs = require("fs"),
    path = process.cwd();

fs.readdir(path, function(err, files){
    if(err){
        return console.log(err);
    }
    for(var i = 0; i < files.length; i += 1){
        console.log(files[i]);
    }
});

上面的”#! /usr/bin/env node”被称为shebang,表示用后面的路径所示的程序来执行当前文件。然后我们需要新建一个package.json文件,内容如下:

{
    "name": "nodefoler",
    "version": "0.0.1",
    "description": "List all the files in a directory!",
    "preferGlobal": "true",
    "bin": { "nf": "nodefolder.js" },
    "author": "steel1990",
    "engines": { "node": "*" }
}

上面的bin字段中,nf是命令行的名字,nodefolder.js是要执行的文件,然后需要使用npm来使命令nf可以在整个系统下执行。在当前目录下执行:

npm link

这样一个命令行工具就完成了,而且你对上面的文件进行任何修改都会立即有效。下面是截图:

命令行执行结果

nodefolder已经完美运行了,通过npm可以快速将创建的命令行工具发布(npm publish)到网上,而需要的用户也可以很快速的获取(npm install)。

注:node最好更新到最新版本。

参考资料

Command line Node.js Programs / Scripts / Utilities / Modules
node.js官网
npm官网
node.js中文社区
shebang

\=======================================================================================

[Command line Node.js Programs / Scripts / Utilities / Modules](http://www.hacksparrow.com/commandline-node-js-scripts-utilities-modules.html "Permanent Link: Command line Node.js Programs / Scripts / Utilities / Modules")

Posted on February 26th, 2012 under Node.js

Tags: command line, node.js

How to write command line programs in Node.js

Ever wondered how to create command line Node.js scripts? If not, go through Node's in-built modules like Child Process, File System, Readline, and Process and see if they inspire you in any way. If not, you can skip this post. Else, this post will take you to the next level of Node Fu.

We will write a command line utility called nodels, which will work something like the Linux ls command with the -la option.

Let's set up the project:

$ mkdir nodels
$ cd nodels
$ touch nodels.js

Use a text editor and copy the following to nodels.js.

var exec = require('child_process').exec;
var child = exec('ls -la', function(err, stdout, stderr) {
    if (err) throw err;
    else console.log(stdout);
});

nodels.js is a functional command line script, you can execute it this way:

$ node nodels.js 
total 12
drwxrwxr-x 2 hacksparrow hacksparrow 4096 2012-02-26 11:58 .
drwx------ 7 hacksparrow hacksparrow 4096 2012-02-26 11:17 ..
-rw-rw-r-- 1 hacksparrow hacksparrow  153 2012-02-26 11:58 nodels.js

Ok that's cool, but what's with the extra node infront of the script? Can't it be more integrated?

We are having to type node infront of the script to execute it using node. Just a line of code at the top of the script can fix it. It tells the system what to execute the script with.

#! /usr/bin/env node
var exec = require('child_process').exec;
var child = exec('ls -la', function(err, stdout, stderr) {
    if (err) throw err;
    else console.log(stdout);
});

Now change the permissions of the script to make it executable and run it just as you would any script.

$ chmod 755 nodels.js
$ ./nodels.js 
total 12
drwxrwxr-x 2 hacksparrow hacksparrow 4096 2012-02-26 12:10 .
drwx------ 7 hacksparrow hacksparrow 4096 2012-02-26 11:17 ..
-rwxr-xr-x 1 hacksparrow hacksparrow  175 2012-02-26 12:10 nodels.js

Can we do away with ./ and make it work like a real Linux command? You know, just execute it without any prefixes and stuff. I have seen some Node modules work like that, Express.js for example.

Good news - yes, you can. But it comes at a small price - you need to create a Node module, a global one.

Create a package.json file in the directory to mark it as a Node module directory:

$ touch package.json

Add the following to package.json:

{
    "name": "nodels",
    "version": "0.0.1",
    "description": "List all the files in a directory, even hidden ones!",
    "preferGlobal": "true",
    "bin": { "nodels": "nodels.js" },
    "author": "Hack Sparrow ",
    "engines": { "node": "*" }
}

Note the bin field. nodels is the name of our command, nodels.js is the file that will do the execution.

Now link the module to make it available system-wide.

$ npm link

If you make any changes to the package.json bin field, you will need to link the project again for the changes to take effect.

Now nodels is available as a system command. Let's give it a spin:

$ nodels
total 16
drwxrwxr-x 2 hacksparrow hacksparrow 4096 2012-02-26 12:31 .
drwx------ 7 hacksparrow hacksparrow 4096 2012-02-26 11:17 ..
-rwxr-xr-x 1 hacksparrow hacksparrow  174 2012-02-26 12:28 nodels.js
-rw-rw-r-- 1 hacksparrow hacksparrow  278 2012-02-26 12:30 package.json

Wooohooo! There you have it - your own command, your own system utility written in Node.js.

Though you have created a command line utility using Node.js, it is confined only to your system. Want to create a global Node module that everyone can install using NPM? Read this post on creating NPM packages.


>> 留言评论