1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

nodeで対話型のCLIを作る。

Posted at

コマンドライン受付部分を作る

index.js
const readline = require('readline');
require('dotenv').config();
const Handler = require('./cli/handler');

const start = async ()=>{

	await Handler.init();//起動と同時にやる処理
	
	//準備
	const reader = readline.createInterface({
		input: process.stdin,  // 標準入力
		output: process.stdout, // 標準出力
		prompt :'やること入力して> '
	});



	// Enterキー押下で読み込み
	reader.on('line', async (line) => {
		if(line !== ''){
			//入力を取得して、コマンドと引数に分ける
			const args = line.split(/\s+/);
			const cmd = args.shift();
			//Handlerの中の関数を実行する
			await Handler[cmd](args);		
		}else{
			console.log('');
		}
		reader.prompt();
	});

	// ctrl+Cで終了
	reader.on('close', () => {
		console.log("finish");
	});

	// コマンドプロンプトを表示
	reader.prompt();
}
//実行
start();

##実行するコマンドを定義する

handler.js
const Hogehoge = require('../app/hogehoge');

const handler = {
	'init': async (args)=>{
		console.log('システムにログインする');
		await Hogehoge.fugafuga();
		console.log('ログイン完了');
	},
	comandFuga:async()=>{
		console.log('comandFugaを実行');
		await Hogehoge.fuga();
		console.log('完了')
	},
	's': async(args)=>{
		console.log('オレオレコマンドなら、1文字のコマンドの方がいいよね');
		await Hogehoge.search(args);
		console.log('表示完了');
	},
};
module.exports = handler;
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?