我有一點空閒時間,所以我決定用子進程重寫JavaScript中的所有bash腳本(NodeJS - ES6)。一切都很順利,直到我想讓用戶輸入自動化。有什麼方法可以確定一個nodejs childprocess是想要輸入還是隻是發送反饋?
是的,你可以自動執行用戶輸入。但有一個問題 - 您無法確定給定的data
事件是反饋還是輸入請求。至少我找不到辦法做到這一點。
所以基本上你可以這樣做:
// new Spawn.
let spawn = require('child_process');
// new ufw process.
let ufw = spawn('ufw', ['enable']);
// Use defined input.
ufw.stdin.setEncoding('utf-8');
ufw.stdout.pipe(process.stdout);
ufw.stdin.write('y\n');
// Event Standard Out.
ufw.stdout.on('data', (data) => {
console.log(data.toString('utf8'));
});
// Event Standard Error.
ufw.stderr.on('data', (err) => {
// Logerror.
console.log(err);
});
// When job is finished (with or without error) it ends up here.
ufw.on('close', (code) => {
// Check if there were errors.
if (code !== 0) console.log('Exited with code: ' + code.toString());
// End input stream.
ufw.stdin.end();
});
上面的例子中工作完全正常。但有兩兩件事給我一個頭痛:
會直到需要
ufw.stdin.write('y\n');
等待,如果我有多個輸入時會發生什麼?例如'是','是','否'。我需要寫3行stdin.write()
嗎?是不是我使用
ufw.stdin.write('y\n');
有點混淆的位置?在我的提示提出輸入請求後,我想我需要輸入信息,所以我決定更改我的代碼,以便我的stdin.write()
能夠在正確的時間運行,理解正確嗎?但是,只有在stdout.on('data', callback)
事件中檢查「正確」時間的唯一方法。這使得認爲有點困難,因爲我需要知道,如果提示aksing供用戶輸入或不...
這裏是我的代碼,我認爲這是完全錯誤的:
// new Spawn.
let spawn = require('child_process');
// new ufw process.
let ufw = spawn('ufw', ['enable']);
// Event Standard Out.
ufw.stdout.on('data', (data) => {
console.log(data.toString('utf8'));
// Use defined input.
ufw.stdin.setEncoding('utf-8');
ufw.stdout.pipe(process.stdout);
ufw.stdin.write('y\n');
});
// Event Standard Error.
ufw.stderr.on('data', (err) => {
// Logerror.
console.log(err);
});
// When job is finished (with or without error) it ends up here.
ufw.on('close', (code) => {
// Check if there were errors.
if (code !== 0) console.log('Exited with code: ' + code.toString());
// End input stream.
ufw.stdin.end();
});
我的主要誤解是何時使用stdin
進行用戶輸入(自動)以及將它放在我的代碼中以便它在正確的時間使用,例如,如果我有多個輸入,例如mysql_secure_installation
。