乐趣区

关于node.js:node-管理子文件夹js文件执行

运行 node 服务,应用 child_process 管制子文件夹 js 文件执行

文件架构:

index.js 主程序入口
fileHelper.js 文件夹遍历
readjson->main.js 子文件夹可执行文件入口 

package.json

{
  "name": "nodelearn",
  "version": "1.0.0",
  "description": "","main":"src/index.js","scripts": {"test":"echo \"Error: no test specified\" && exit 1"},"keywords": [],"author":"",
  "license": "ISC"
}

index.js

const {spawn} = require("child_process");
const readline = require("readline");
const rl = readline.createInterface({input: process.stdin, output: process.stdout});
const {loopFileSync} = require("./fileHelper");

const entryFileName = "main.js";
const stratys = [];// 待执行办法
let aheadMessages = [];// 通用执行

// 获取所有可执行文件
const files = loopFileSync(__dirname);

files.forEach(item => {const { fileName, fileDir, fileStat} = item;
    if (fileName === entryFileName) {let fileDirSplit = fileDir.split("\\");
        if (fileDirSplit.length < 2) return;
        stratys.push([fileDirSplit[fileDirSplit.length - 2], fileDir, fileStat]);
    }
})

// 进入用户抉择
function execution(cb) {console.clear();

    let showMessage = "";
    aheadMessages = [];

    showMessage += "please select your choose.\n";

    aheadMessages.push("0、exit\n");
    aheadMessages.push("1、run lastest modify\n");
    aheadMessages.push("2、run lastest create\n");
    aheadMessages.push("3、run all\n");

    showMessage += aheadMessages.join("");

    stratys.forEach((item, index) => {showMessage += `${index + aheadMessages.length}、${item[0]}\n`;
    })

    rl.question(showMessage, function (answer) {cb(answer, () => {rl.question("按回车键持续!", function () {execution(cb);
            })
        });
    })
}

function createNodeExecPromiseFactory(processName, jsFile) {return new Promise((resolve) => {
        let data = '';
        let spawnObj = spawn("node", [jsFile], {'shell': true});
        spawnObj.stdout.on("data", (chunk) => {data += chunk.toString();
        })
        spawnObj.on("exit", () => {console.log(`${new Date().toLocaleString()}----- 开始执行工作:${processName}`);
            console.log(data);
            console.log(`${new Date().toLocaleString()}----- 执行工作 ${processName} 结束 `);
            resolve();})
    })
}

function handleExecution(choose, next) {let chooseNum = Number(choose);
    if (isNaN(chooseNum) || chooseNum < 0 || chooseNum > (stratys.length + aheadMessages.length - 1)) {console.warn("抉择有误, 请从新抉择!");
        next();
        return;
    }
    if (chooseNum == 0) {console.log("Exit!");
        rl.close();
        process.exit(0);
    }
    console.clear();
    let newStratys = [], promises = [];
    switch (chooseNum) {
        case 1: // 按批改工夫排序, 执行最新批改
            newStratys = stratys.slice().sort((a, b) => {return b[2].mtimeMs - a[2].mtimeMs;
            })
            promises.push(createNodeExecPromiseFactory(newStratys[0][0], newStratys[0][1]));
            break;
        case 2: // 按创立工夫排序, 执行最新创立
            newStratys = stratys.slice().sort((a, b) => {return b[2].ctimeMs - a[2].ctimeMs;
            })
            promises.push(createNodeExecPromiseFactory(newStratys[0][0], newStratys[0][1]));
            break;
        case 3:// 执行全副工作
            newStratys = stratys;
            for (let i = 0; i < newStratys.length; i++) {promises.push(createNodeExecPromiseFactory(newStratys[i][0], newStratys[i][1]));
            }
            break;
        default:
            newStratys = stratys;
            let _chooseNum = chooseNum - aheadMessages.length;
            promises.push(createNodeExecPromiseFactory(newStratys[_chooseNum][0], newStratys[_chooseNum][1]));
            break;
    }
    const p = Promise.all(promises);

    p.then(() => {console.log("执行所有工作结束!");
        next();})
}

execution(handleExecution);

fileHelper.js

const fs = require("fs");
const path = require("path");

function loopFile(filePath, cb) {fs.readdirSync(filePath, function (err, files) {if (err) {console.warn(err)
        } else {files.forEach(function (filename) {var filedir = path.join(filePath, filename);
                fs.stat(filedir, function (eror, stats) {if (eror) {console.warn('获取文件 stats 失败');
                    } else {var isFile = stats.isFile();
                        var isDir = stats.isDirectory();
                        if (isFile) {if (typeof cb === "function") cb(filename, filedir,fileStat);
                        }
                        if (isDir) {loopFile(filedir, cb);
                        }
                    }
                })
            });
        }
    });
}

function loopFileSync(filePath) {const result = [];
    function loop(filePath) {let files = fs.readdirSync(filePath);
        files.forEach(function (fileName) {let fileDir = path.join(filePath, fileName);
            let fileStat = fs.statSync(fileDir);
            if (fileStat.isFile()) {result.push({ fileDir, fileName,fileStat});
            } else if (fileStat.isDirectory()) {loop(fileDir);
            }
        });
    }
    loop(filePath);
    return result;
}

exports.loopFile = loopFile;
exports.loopFileSync = loopFileSync;

运行成果

退出移动版