node.js 记录一个自动监听拷贝文件到目标文件的demo

用途

  1. 前后端分离项目
  2. 前端项目打包后拷贝对应的打包文件(一般为dist文件夹)到服务端文件夹(一般为public文件夹)中去

使用

npm install
复制代码

命令说明

npm run test : 运行拷贝命令
npm run pmcopy: 进程管理拷贝 (存在问题,不建议执行)
npm run build:直接运行vue项目中的npm run build,方便执行

copy.js 说明,详见copy.js

未解决的问题

pm2 执行后会使vue中的dist文件夹中的部分文件变成需要管理员权限执行问题,后续再执行npm run build 会报不被允许访问错误,需杀死pm2后才能解除,目前未找到原因

以下为相关代码

copy.js

var fs = require('fs'),
    stat = fs.stat;
var chokidar = require('chokidar');

/*
05
 * 复制目录中的所有文件包括子目录
06
 * @param{ String } 需要复制的目录
07
 * @param{ String } 复制到指定的目录
08
 */
var copy = function (src, dst) {
    // 读取目录中的所有文件/目录
    fs.readdir(src, function (err, paths) {
        if (err) {
            throw err;
        }

        paths.forEach(function (path) {
            var _src = src + '/' + path,
                _dst = dst + '/' + path,
                readable, writable;

            stat(_src, function (err, st) {
                if (err) {
                    throw err;
                }

                // 判断是否为文件
                if (st.isFile()) {
                    // 创建读取流
                    readable = fs.createReadStream(_src);
                    // 创建写入流
                    writable = fs.createWriteStream(_dst);
                    // 通过管道来传输流
                    readable.pipe(writable);
                }
                // 如果是目录则递归调用自身
                else if (st.isDirectory()) {
                    exists(_src, _dst, copy);
                }
            });
        });
    });
};
// 在复制目录前需要判断该目录是否存在,不存在需要先创建目录
var exists = function (src, dst, callback) {
    fs.exists(dst, function (exists) {
        // 已存在
        if (exists) {
            callback(src, dst);
        }
        // 不存在
        else {
            fs.mkdir(dst, function () {
                callback(src, dst);
            });
        }
    });
};

// 删除所有文件夹
function deleteall(path) {
    let files = [];
    if (fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach(function (file, index) {
            // console.log(file);
            let curPath = path + "/" + file;
            console.log(curPath);
            if (fs.statSync(curPath).isDirectory()) { // recurse
                deleteall(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};
// 需要拷贝的源文件夹
const dirFrom = './marketing.shenkonghao.UI/dist'
// 拷贝的目标文件夹
const dirTo = './marketing-shenkonghao-node/app/public'
// const dirTo = './haha'

// 创建一个监听器,监听文件的变化
var watcher = chokidar.watch(dirFrom, {
    ignored: /[\/\\]\./, persistent: true
});
var log = console.log.bind(console);

watcher
    .on('add', function (path) {
        // 删除目标文件中的文件
        deleteall(dirTo)
        // 复制目录文件到目标文件
        exists(dirFrom, dirTo, copy);
        log('File', path, 'has been added');
    })
    .on('addDir', function (path) { log('Directory', path, 'has been added'); })
    .on('change', function (path) {
        log('File', path, 'has been changed');
        // 删除目标文件中的文件
        deleteall(dirTo)
        // 复制目录文件到目标文件
        exists(dirFrom, dirTo, copy);
    })
    .on('unlink', function (path) { log('File', path, 'has been removed'); })
    .on('unlinkDir', function (path) { log('Directory', path, 'has been removed'); })
    .on('error', function (error) { log('Error happened', error); })
    .on('ready', function () { log('Initial scan complete. Ready for changes.'); })
    .on('raw', function (event, path, details) { log('Raw event info:', event, path, details); })
复制代码

package.json部分

{
  "name": "shengkong",
  "version": "1.0.0",
  "description": "进程守护,监听文件变化并复制文件到目标文件夹",
  "main": "copy.js",
  "scripts": {
    "test": "node copy.js",
    "pmcopy":"pm2 start copy.js",
    "vuebuild":"cd ./marketing.shenkonghao.UI && npm run build"
  },
  "author": "shenqiang",
  "license": "ISC",
  "dependencies": {
    "chokidar": "^3.5.1",
    "fs": "0.0.1-security"
  }
}

复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享