現在寫 PHP 的時候都會試著在 node.js 以及 shell script 上實現,所以會不斷的嘗試程式碼,每次要看執行結果都要下一次 command 也挺累的,寫了一隻 w.js 來監控這三種檔案的變動並帶入對應的呼叫方式來節省時間
此功能需安裝 watch,執行方法為 node w.js xxx.php
w.js
const watch = require('watch');
const { exec } = require('child_process');
const path = require('path');
const argvs = process.argv;
const target = argvs[2];
const fs = require('fs');
const commandMap = {
sh: 'bash',
php: 'php',
js: 'node'
};
if (target === undefined) {
console.log('Need file argument!');
return;
}
if (!fs.existsSync(target)) {
console.log(`${target} is not exists!`);
return;
}
let ext = path.extname(target).replace(/\./g, '');
if (Object.keys(commandMap).indexOf(ext) === -1) {
console.log(`${ext} is not legal!`);
return;
}
console.log(`Start to watch "${target}"!`);
watch.createMonitor('./', (monitor) => {
monitor.on('changed', (file) => {
if (file === target) {
exec(`clear; ${commandMap[ext]} ${file}`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(stdout);
console.log(stderr);
});
}
});
});
實際使用畫面大概是這樣