使用 Node.js 和 Git 自动化部署项目

在现代开发中,自动化部署是提高工作效率和减少人为错误的重要手段。本文将介绍如何使用 Node.js 和 Git 实现一个简单的自动化部署脚本,帮助你在打包完成后自动将文件上传到指定的 Git 仓库。

项目结构

我们将创建一个名为 deploy.js 的文件,其中包含了自动化部署的逻辑。以下是项目的基本结构:

/your-project

├── deploy.js

└── ... (其他项目文件)

代码实现

1. 引入必要的模块

首先,我们需要引入一些 Node.js 的核心模块和第三方库:

const fs = require("fs");

const path = require("path");

const simpleGit = require('simple-git');

  • fs:用于文件系统操作。

  • path:用于处理文件路径。

  • simple-git:用于简化 Git 操作。

2. 配置基本参数

接下来,我们定义一些基本参数,包括源目录、目标目录和要排除的目录:

javascript 复制代码
let git;

const sourceDir = 'C:\\Users\\86354\\Desktop\\mywork\\web';

const targetDir = 'C:\\Users\\86354\\Desktop\\myproject\\web';

const excludedDir = 'media';

3. 初始化 Git

我们创建一个 initGit 函数,用于初始化 Git 并执行拉取、切换分支和推送操作: 作:

javascript 复制代码
async function initGit(mode) {

    const options = {

        baseDir: process.cwd(),

        binary: 'git',

        maxConcurrentProcesses: 6,

        trimmed: false,

    };

    git = simpleGit(targetDir);

    try {

        console.log('Pulling changes...');

        await git.pull();

        let branch = mode == 'test' ? 'test' : 'main';

        await git.checkout(branch);

        await git.pull();

        await deleteNonMediaFiles(targetDir);

        await copyFolderContentsWithoutExcludedDir(sourceDir, targetDir, excludedDir);

        await git.add('./*');

        await git.commit('add-auto');

        await git.push();

        console.log('git推送成功');

    } catch (error) {

        console.error('Error occurred during Git operations:', error);

    }

}

4. 删除非指定目录的文件

我们定义一个 deleteNonMediaFiles 函数,用于删除目标目录中除 media 目录外的所有文件和子目录:

javascript 复制代码
async function deleteNonMediaFiles(currentPath) {
    const entries = await fs.promises.readdir(currentPath, { withFileTypes: true });
    for (const entry of entries) {
        const entryPath = path.join(currentPath, entry.name);
        if (entry.isDirectory() && entry.name !== 'media') {
            await deleteNonMediaFiles(entryPath);
            await fs.promises.rmdir(entryPath);
        } else if (!entry.isDirectory()) {
            await fs.promises.unlink(entryPath);
        }
    }
}

5. 复制文件夹内容

接下来,我们实现一个 copyFolderContentsWithoutExcludedDir 函数,用于复制源目录的内容到目标目录,但排除指定的子目录:

javascript 复制代码
async function copyFolderContentsWithoutExcludedDir(source, destination, excludedDirName) {

    if (!fs.existsSync(source)) {

        throw new Error(`Source directory ${source} does not exist.`);

    }

    await fs.promises.mkdir(destination, { recursive: true });

    const entries = await fs.promises.readdir(source, { withFileTypes: true });

    for (const entry of entries) {

        const sourceEntryPath = path.join(source, entry.name);

        const destinationEntryPath = path.join(destination, entry.name);

        if (entry.isDirectory() && entry.name === excludedDirName) {

            continue;

        }

        if (entry.isDirectory()) {

            await copyFolderContentsWithoutExcludedDir(sourceEntryPath, destinationEntryPath, excludedDirName);

        } else {

            await fs.promises.copyFile(sourceEntryPath, destinationEntryPath);

        }

    }

}

6. 创建插件

最后,我们创建一个 UploadDistPlugin 类,用于在打包完成后自动执行部署操作:

javascript 复制代码
class UploadDistPlugin {

    constructor(options) {

        this.options = options;

    }

    apply(compiler) {

        compiler.hooks.done.tap('UploadDistPlugin', (stats) => {

            const currentMode = process.argv[3] == '--test' ? 'test' : 'production';

            if (process.env.NODE_ENV !== 'development') {

                initGit(currentMode);

            }

        });

    }

}

总结

通过以上步骤,我们实现了一个简单的自动化部署脚本,能够在打包完成后将文件上传到指定的 Git 仓库。这个脚本可以根据需要进行扩展和修改,以适应不同的项目需求。

相关推荐
月下点灯2 小时前
🔄记住这张图,脑子跟着浏览器的事件循环(Event Loop)转起来了
前端·javascript·浏览器
邹小邹-AI2 小时前
Rust + 前端:下一个十年的“王炸组合”
开发语言·前端·rust
行走在顶尖2 小时前
vue3+ant-design-vue
前端
华仔啊3 小时前
图片标签用 img 还是 picture?很多人彻底弄混了!
前端·html
lichong9513 小时前
XLog debug 开启打印日志,release 关闭打印日志
android·java·前端
烟袅3 小时前
作用域链 × 闭包:三段代码,看懂 JavaScript 的套娃人生
前端·javascript
风止何安啊3 小时前
收到字节的短信:Trae SOLO上线了?尝尝鲜,浅浅做个音乐播放器
前端·html·trae
抱琴_3 小时前
大屏性能优化终极方案:请求合并+智能缓存双剑合璧
前端·javascript
用户463989754323 小时前
Harmony os——长时任务(Continuous Task,ArkTS)
前端
fruge3 小时前
低版本浏览器兼容方案:IE11 适配 ES6 语法与 CSS 新特性
前端·css·es6