Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8696

Node.js 簡単な応答バッチ処理

$
0
0

はじめに

Node.jsでyまたはnの応答に従い、バッチ処理を実行するJavaSciptのサンプルを作成しました。
この辺、Promiseとasync/awaitなどを利用して対話的に同期処理を実行すると分けがわからなくところです。
初学者向けと自らの備忘録で掲載します。

前提

バッチ処理リスト

  • batchlist.json
[{"msg":"★ ★ リストを確認します。(ls) 実行 = y, 中止 = n ★ ★","con":"y","can":"n","cmd":"ls"},{"msg":"★ ★ パスを確認します。(pwd) 実行 = y, 中止 = n ★ ★","con":"y","can":"n","cmd":"pwd"}]

JSON項目説明

項目説明
msg応答文、実行と中止を定義
con実行(continu)の文字列を定義
can中止(cancel)の文字列を定義
cmd実行するコマンド(command)を定義

バッチ処理スクリプト

  • Dobatch.js
constexec=require('child_process').execFileSync;constfs=require('fs');constjson=JSON.parse(fs.readFileSync('./batchlist.json','utf8'));// コンソール標準入出力constrl=require("readline").createInterface(process.stdin,process.stdout);constgets=()=>newPromise(res=>rl.once("line",res));/**
 * コマンドラッパー(同期処理)
 * @param {String } cmd - コマンド
 */functionsh(cmd){try{console.log(exec(cmd,{shell:true}).toString());}catch(error){console.log(error.stderr.toString());}}// バッ処理実行(asyncfunction(){for(vari=0;json.length>i;i++){console.log(json[i].msg);str=awaitgets();if(str==json[i].con){console.log(json[i].cmd);sh(json[i].cmd);}elseif(str==json[i].can){process.exit();}else{console.log(str+"は入力不正です。")i--;}}process.exit();})();

説明

  • コマンド実行はchild_processのexecFileSyncを利用して同期処理
  • JSONの読み出しもfsのreadFileSyncを利用して同期処理
  • 残るは、コンソールからの入出力応答をPromoiseとasync/awaitで同期処理
    gets関数で定義

実行

Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

PS C:\Users\~>bash --version ...①
GNU bash, version 4.4.12(2)-release(x86_64-pc-msys)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
PS C:\Users\~>bash ...②
USER MINGW64 ~/
$ node Dobatch.js ...③
★ ★ リストを確認します。(ls)実行 = y, 中止 = n ★ ★
y
ls
batchlist.json
Dobatch.js

★ ★ パスを確認します。(pwd)実行 = y, 中止 = n ★ ★
y
pwd
/c/Users/~/


USER MINGW64 ~/
$

説明

① bashのバージョン確認
② PowerShellからbashへ切替え
③ Dobatch.jsの実行

※ 実行で表示されるパスは出力を編集して表示しています。

まとめ

Node.jsのコンソールからの標準入力がめんどくさい、VBのMsgBox的なコーディングをしようとして悪戦苦闘した記憶がありました。ファイルの読み込みとコマンド実行を同期処理にすれば、以外と簡単にできると思います。たぶレスポンスはいまいちだと思います。
色々なシステム導入ツールがあると思いますが、JSONファイルのバッチ定義で簡易システム導入ツールとしてご利用してみてください。ただし、参考までに、例によって一切のご利用はあくまでも自己責任でお願いします。


Viewing all articles
Browse latest Browse all 8696

Trending Articles