likes
comments
collection
share

node 管理子文件夹js文件执行

作者站长头像
站长
· 阅读数 22

运行node服务,使用child_process控制子文件夹js文件执行

文件架构:

node 管理子文件夹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;

运行效果

node 管理子文件夹js文件执行

node 管理子文件夹js文件执行