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

相关推荐
卡布叻_星星21 分钟前
Docker之Nginx前端部署(Windows版-x86_64(AMD64)-离线)
前端·windows·nginx
LYFlied21 分钟前
【算法解题模板】-解二叉树相关算法题的技巧
前端·数据结构·算法·leetcode
weibkreuz24 分钟前
React的基本使用@2
前端·javascript·react.js
于是我说27 分钟前
前端JavaScript 项目中 获取当前页面滚动位置
开发语言·前端·javascript
GISer_Jing28 分钟前
AI在前端开发&营销领域应用
前端·aigc·音视频
Hao_Harrision37 分钟前
50天50个小项目 (React19 + Tailwindcss V4) ✨ | DragNDrop(拖拽占用组件)
前端·react.js·typescript·tailwindcss·vite7
来杯三花豆奶1 小时前
Vue 2.0 Mixins 详解:从原理到实践的深度解析
前端·javascript·vue.js
code_YuJun1 小时前
脚手架开发工具——dotenv
前端
San30.1 小时前
深度驱动:React Hooks 核心之 `useState` 与 `useEffect` 实战详解
前端·javascript·react.js
Mr_Swilder1 小时前
vscode没有js提示:配置jsconfig配置
前端