LoginSignup
10
11

More than 5 years have passed since last update.

nodeの関数をbashシェルで使えるようにする。

Last updated at Posted at 2013-11-13

Nodeの関数をbashターミナルから使いたい

いちいち、nodeの対話環境を使うのも面倒な話なので、直接呼べると便利
node の関数とモジュールは幸い2階層なので、以下のようにすることでシェルスクリプトでパイプ経由で使えるようになる。

前準備

node関数をコマンドして使う

sample1
bash> git clone https://gist.github.com/f5a6fb560dc357835122.git
bash> chmod +x node2bash.js
bash>  ln -s node2bash.js /usr/local/bin/encodeURIComponent
bash>  ln -s node2bash.js /usr/local/bin/decodeURIComponent
bash>  ln -s node2bash.js /usr/local/bin/querystring.parse

使用例

bash から uri エンコードする

sample2
bash>  encodeURIComponent 'aaa=1&bb=あああ'
aaa%3D1%26bb%3D%E3%81%82%E3%81%82%E3%81%82

パイプ経由でも

sample3
bash > encodeURIComponent 'aaa=1&bb=あああ' | decodeURIComponent
aaa=1&bb=あああ

標準入出力を使ってパイプパイプ

bash から uri エンコードしたのをデコードしたのをQueryString分割して、JSONにする。

bash> echo  'aaa=1&bb=あああ'  | encodeURIComponent| decodeURIComponent | querystring.parse
{ aaa: '1', bb: 'あああ' } 

以下のコードをベースに使います。

node2bash.js
#!/usr/bin/env node
/***
 * author takuya_1st
 * Released under  GPL Licenses.
 * Date: 2013-11-21 2:06
 */
var fs   = require('fs')
var path = require('path');
var name = process.argv[1];
var str  = process.argv[2];

//モジュールの処理
if( name.match(/\./) ){
    module_name = path.basename( name.split(/\./).shift()) ;
    name = name.split(/\./).pop();
    if( global[module_name] ){
      module = global[module_name];
    }else{
      module = require(module_name);
    }
}else {
    name =  path.basename(name);
    module = global;
}
//コマンドシェルで実行したい関数
var func = module[name];



if(str) {
    if(fs.existsSync(str)){
        str = fs.readFileSync(str);
    }
    str  = func(str);
    console.log(str);
}else{
    process.stdin.resume();
    process.stdin.setEncoding('utf8');

    var lines = []
        // 標準入力がくると発生するイベント
        process.stdin.on('data', function (chunk) {

                lines.push(chunk.trim())
                });
    // EOFがくると発生するイベント
    process.stdin.on('end', function () {
            lines = lines.join("\n")
            console.log( func(lines)  )
            });

}

ぶっちゃけた話、nodeコマンドの対話シェルやnodeでスクリプト書くよりbashでコマンドで組み合わせたほうがすごく便利

以前書いた以下の改良版

10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11