Electron からコマンドライン実行

Uncategorized
467 words

Node.js を使ってコマンドライン実行をする方法を紹介します。

Electronアプリの作成

Googleが推奨する マテリアルデザイン が好きなので CSSフレームワーク を読み込んで見た目を変更しています。

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html>
<head>
<title>Hello World!</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</head>
<body>
<div class="container">
<div class="section">
<div class="row">
<div class="input-field col l11">
<input id="inputtext1" type="text" class="validate">
<label for="last_name">シェルコマンド</label>
</div>
<div class="input-field col l1">
<button type="button" class="waves-effect waves-light btn" onclick="run()">実行</a>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea"></textarea>
<label for="textarea1">実行結果</label>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="./index.js"></script>
</body>
</html>

index.js

1
2
3
4
5
6
7
const util = require('util');
const childProcess = require('child_process');
const exec = util.promisify(childProcess.exec);
async function run() {
let result = await exec(document.getElementById('inputtext1').value);
document.getElementById('textarea1').value = result.stdout;
}

ちょっと長いですが、htmlファイルとjsファイルに貼り付けて Electron で読み込めばオシャレな画面が表示されます。

コマンドライン実行

コマンドを入力して 実行ボタンを押せば、実行結果が表示されます。

文字化け対策

え?「文字化けしてるじゃん」ですって?

そーです。コマンドラインは「Shift_JIS」で動作しているので「UNICODE」にエンコーディングしてあげる必要があります。

npm で encoding-japanese モジュール をインストールします。

1
npm install encoding-japanese --save

JavaScript を少し修正します。

1
2
3
4
5
6
7
8
9
10
const util = require('util');
const childProcess = require('child_process');
const exec = util.promisify(childProcess.exec);
const Encoding = require('encoding-japanese'); // npm install encoding-japanese --save
async function run() {
// let result = await exec(document.getElementById('inputtext1').value);
// document.getElementById('textarea1').value = result.stdout;
let result = await exec(document.getElementById('inputtext1').value, { encoding: 'Shift_JIS' });
document.getElementById('textarea1').value = Encoding.convert(result.stdout, { from: 'SJIS', to: 'UNICODE', type: 'string' });
}

これで文字化けしなくなります。

おわりに

Electron はホントに素晴らしいですね。

画面も処理も Webアプリ感覚で作れてしまいます。