使用 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 仓库。这个脚本可以根据需要进行扩展和修改,以适应不同的项目需求。

相关推荐
paopaokaka_luck43 分钟前
基于SpringBoot+Uniapp的健身饮食小程序(协同过滤算法、地图组件)
前端·javascript·vue.js·spring boot·后端·小程序·uni-app
患得患失9491 小时前
【前端】【vscode】【.vscode/settings.json】为单个项目配置自动格式化和开发环境
前端·vscode·json
飛_1 小时前
解决VSCode无法加载Json架构问题
java·服务器·前端
YGY Webgis糕手之路4 小时前
OpenLayers 综合案例-轨迹回放
前端·经验分享·笔记·vue·web
90后的晨仔4 小时前
🚨XSS 攻击全解:什么是跨站脚本攻击?前端如何防御?
前端·vue.js
Ares-Wang4 小时前
JavaScript》》JS》 Var、Let、Const 大总结
开发语言·前端·javascript
90后的晨仔4 小时前
Vue 模板语法完全指南:从插值表达式到动态指令,彻底搞懂 Vue 模板语言
前端·vue.js
德育处主任5 小时前
p5.js 正方形square的基础用法
前端·数据可视化·canvas
烛阴5 小时前
Mix - Bilinear Interpolation
前端·webgl
90后的晨仔5 小时前
Vue 3 应用实例详解:从 createApp 到 mount,你真正掌握了吗?
前端·vue.js