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

相关推荐
excel7 分钟前
前端人必备的 JavaScript API 全面指南(含 postMessage、File、Stream、Web 组件等)
前端
m0_738120725 小时前
CTFshow系列——命令执行web53-56
前端·安全·web安全·网络安全·ctfshow
Liu.7747 小时前
uniappx鸿蒙适配
前端
山有木兮木有枝_8 小时前
从代码到创作:探索AI图片生成的神奇世界
前端·coze
言兴8 小时前
秋招面试---性能优化(良子大胃袋)
前端·javascript·面试
WebInfra10 小时前
Rspack 1.5 发布:十大新特性速览
前端·javascript·github
雾恋10 小时前
我用 trae 写了一个菜谱小程序(灶搭子)
前端·javascript·uni-app
烛阴11 小时前
TypeScript 中的 `&` 运算符:从入门、踩坑到最佳实践
前端·javascript·typescript
Java 码农12 小时前
nodejs koa留言板案例开发
前端·javascript·npm·node.js
ZhuAiQuan12 小时前
[electron]开发环境驱动识别失败
前端·javascript·electron