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

相关推荐
csgo打的菜又爱玩3 小时前
Vue 基础(实战模板与命名指南)
前端·javascript·vue.js
ding_zhikai4 小时前
SD:在一个 Ubuntu 系统安装 stable diffusion Web UI
前端·ubuntu·stable diffusion
gerrgwg5 小时前
Vue-library-start,一个基于Vite的vue组件库开发模板
前端·javascript·vue.js
你的人类朋友6 小时前
【Node】单线程的Node.js为什么可以实现多线程?
前端·后端·node.js
iナナ7 小时前
Spring Web MVC入门
java·前端·网络·后端·spring·mvc
驱动探索者7 小时前
find 命令使用介绍
java·linux·运维·服务器·前端·学习·microsoft
开心不就得了7 小时前
自定义脚手架
前端·javascript
星晨雪海9 小时前
怎么格式化idea中的vue文件
前端·vue.js·intellij-idea
没事多睡觉6669 小时前
Vue 虚拟列表实现方案详解:三种方法的完整对比与实践
前端·javascript·vue.js
white-persist9 小时前
Burp Suite模拟器抓包全攻略
前端·网络·安全·web安全·notepad++·原型模式