Skip to content

plugin_require

引入 Node.js 模块,使插件能够使用 Node.js 生态系统中的任何模块。

函数签名

javascript
plugin_require(moduleName: string): any

参数说明

参数类型必填说明
moduleNamestring要引入的模块名称

参数详解

  • moduleName:要引入的模块名称,支持以下类型:
    • Node.js 内置模块:如 "fs""path""http""crypto"
    • 第三方 npm 包:如 "axios""moment""sqlite3" 等,需要先在项目根目录安装

返回值

返回引入的模块对象,具体结构取决于模块本身。

功能描述

plugin_require 是插件访问 Node.js 生态系统的桥梁。通过这个函数,插件可以引入任何 Node.js 模块,从而实现文件操作、网络请求、数据库访问等高级功能。这使得 MSL 插件具有了几乎无限的可扩展性。

与标准的 require 函数不同,plugin_require 是在插件沙箱环境中提供的,确保了插件的安全隔离。所有通过 plugin_require 引入的模块都在沙箱的上下文中运行。

使用示例

引入内置模块

javascript
// 引入文件系统模块
const fs = plugin_require("fs");
const path = plugin_require("path");

// 读取配置文件
const configPath = path.join(__dirname, "config.json");
const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
plugin_log("INFO", `配置加载成功: ${config.name}`);

引入 HTTP 模块

javascript
const http = plugin_require("http");
const https = plugin_require("https");

// 发送 HTTP 请求
function fetch(url) {
    return new Promise((resolve, reject) => {
        const client = url.startsWith("https") ? https : http;
        client.get(url, (res) => {
            let data = "";
            res.on("data", chunk => data += chunk);
            res.on("end", () => resolve(data));
        }).on("error", reject);
    });
}

// 使用示例
plugin_onEvent("playerJoin", async (time, player) => {
    try {
        const response = await fetch(`https://api.mojang.com/users/profiles/minecraft/${player}`);
        plugin_log("INFO", `玩家数据: ${response}`);
    } catch (error) {
        plugin_log("ERROR", `请求失败: ${error.message}`);
    }
});

引入第三方模块

首先安装模块:

bash
npm install axios

然后在插件中使用:

javascript
const axios = plugin_require("axios");

// 发送 Webhook 通知
async function sendWebhook(url, data) {
    try {
        await axios.post(url, data);
        plugin_log("INFO", "Webhook 发送成功");
    } catch (error) {
        plugin_log("ERROR", `Webhook 发送失败: ${error.message}`);
    }
}

// 玩家加入时发送通知
plugin_onEvent("playerJoin", (time, player) => {
    sendWebhook("https://your-webhook-url", {
        event: "playerJoin",
        player: player
    });
});

引入加密模块

javascript
const crypto = plugin_require("crypto");

// 生成随机令牌
function generateToken() {
    return crypto.randomBytes(16).toString("hex");
}

// 计算哈希
function hash(text) {
    return crypto.createHash("sha256").update(text).digest("hex");
}

// 使用示例
plugin_onEvent("playerJoin", (time, player) => {
    const token = generateToken();
    plugin_log("INFO", `为 ${player} 生成令牌: ${token}`);
});

注意事项

  1. 模块安装:第三方模块需要先在 MSL 项目根目录安装(npm install <package>
  2. 模块缓存:模块在首次引入后会被缓存,重复引入会返回缓存的实例
  3. 异步操作:许多 Node.js 模块支持异步操作,建议使用 async/await 或 Promise 处理
  4. 错误处理:引入不存在的模块会抛出错误,建议使用 try-catch 捕获

相关 API

相关指南