该案例具体命令作用如下

  1. -v,-V output the version number
    2. -d —del 删除当前路径下的所有文件与文件夹
    3. -c —copydir 拷贝文件夹到指定目录
    4. -h, —help display help for command
    5. 当不传入参数,会展示当前node目录下的文件信息

    ! /usr/bin/env node

    const { program } = require(“commander”);
    const fs = require(“fs”);
    const { join } = require(“path”);
    const { extname } = require(“path”)

    let paths = process.cwd();

    program
    .version(“1.0.1”, “-v,-V”)
    .option(“-d —del “, “删除当前路径下的所有文件与文件夹”)
    .option(“-c —copydir”, “拷贝文件夹到指定目录”)
    .action((res, com) => {
    if (com.args.length == 0) {
    readDir(paths);
    } else if (res.del) {
    delFile(join(paths, res.del));
    } else if (res.copydir) {
    copydir(join(paths, com.args[0]), join(paths, com.args[1]))
    }
    })
    .parse(process.argv)

    //删除文件夹
    function delFile(filepath) {
    if (fs.existsSync(filepath)) {
    if (fs.statSync(filepath).isDirectory()) {
    let dirArr = fs.readdirSync(filepath);
    dirArr.forEach(item => {
    delFile(join(filepath, item));
    })
    } else {
    fs.unlinkSync(filepath);
    }
    fs.rmdirSync(filepath);
    } else {
    console.log(“该路径不合法”);
    }
    }

    //克隆文件夹
    function copydir(srcpath, distpath) {
    if (fs.existsSync(srcpath)) {
    !fs.existsSync(distpath) && fs.mkdirSync(distpath);

    1. if (fs.statSync(srcpath).isDirectory()) {<br /> let dirArr = fs.readdirSync(srcpath);
    2. dirArr.forEach(item => {<br /> if (fs.statSync(join(srcpath, item)).isDirectory()) {<br /> copydir(join(srcpath, item), join(distpath, item));<br /> } else {<br /> fs.copyFileSync(join(srcpath, item), join(distpath, item));<br /> }<br /> })<br /> } else {<br /> fs.copyFileSync(srcpath, distpath);<br /> }<br /> } else {<br /> console.log("该路径不合法");<br /> }<br /> }

    //读取当前执行的node目录下的文件信息
    function readDir(dirPath) {
    let dirArr = fs.readdirSync(dirPath);
    let str = “路径” + dirPath + “下的所有文件有:”;

    1. dirArr.forEach(item => {<br /> if (fs.statSync(join(dirPath, item)).isFile()) {<br /> str += `\n\n${item}:<br /> 文件大小:${fs.statSync(join(dirPath, item)).size} <br /> 文件类型:${extname(join (dirPath, item)).substr(1)}`;<br /> }<br /> })
    2. console.log(str);<br /> }