如何使用RequireJS?解决child_process未加载错误并调用server.js执行bash.sh
解决RequireJS加载Node.js模块报错并执行bash脚本的问题
嘿,我来帮你搞定这个问题——你现在踩的坑其实是浏览器环境和Node.js环境的本质差异导致的,咱们一步步理顺:
问题根源拆解
child_process是Node.js专属模块:浏览器是安全沙箱环境,根本没有这个模块,你直接在浏览器里加载依赖它的server.js,肯定会报错。- 加载方式不符合RequireJS规范:你用XMLHttpRequest加载脚本再设置src的方式,破坏了RequireJS的异步模块加载机制,所以才会出现那个“Module not loaded”的提示。
正确解决方案思路
要执行bash脚本,必须让Node.js后端来做这件事(只有后端能访问系统命令),浏览器只需要通过HTTP请求调用后端接口,让后端去执行脚本并返回结果。
第一步:重构后端server.js为接口服务
我们用Express框架做个简单接口(也可以用原生Node.js HTTP模块,Express更省心):
const express = require('express'); const exec = require('child_process').exec; const app = express(); const port = 3000; // 允许跨域,方便前端访问(如果前端和后端不在同一端口) app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET, POST'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }); // 定义执行bash脚本的接口 app.get('/run-script', (req, res) => { exec('./bash.sh', (error, stdout, stderr) => { // 把执行结果打包成JSON返回给前端 const result = { stdout: stdout.trim(), stderr: stderr.trim(), error: error ? error.message : null }; res.json(result); console.log('脚本执行完成:', result); }); }); // 启动后端服务 app.listen(port, () => { console.log(`后端服务跑在 http://localhost:${port} 啦`); });
第二步:修改前端index.html,用RequireJS正确调用接口
我们用RequireJS加载jQuery来发起AJAX请求(你也可以用原生fetch,这里贴合RequireJS的用法):
<html> <body> <h2>执行后端bash脚本</h2> <p id="demo1">点击按钮执行脚本,结果会显示在这里👇</p> <button type="button" onclick="runServerScript()">执行脚本</button> <!-- 引入RequireJS --> <script src="https://requirejs.org/docs/release/2.3.6/comments/require.js"></script> <script type="text/javascript"> function runServerScript() { // 用RequireJS异步加载jQuery,然后发起请求 require(['https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'], function($) { $.get('http://localhost:3000/run-script') .done(function(data) { let output = ''; if (data.stdout) output += `<strong>标准输出:</strong> ${data.stdout}<br>`; if (data.stderr) output += `<strong>错误输出:</strong> ${data.stderr}<br>`; if (data.error) output += `<strong>执行错误:</strong> ${data.error}`; document.getElementById("demo1").innerHTML = output; }) .fail(function(err) { document.getElementById("demo1").textContent = `请求失败啦: ${err.statusText}`; }); }); } </script> </body> </html>
第三步:运行步骤
- 给你的
bash.sh加执行权限(Linux/macOS):chmod +x bash.sh - 安装后端依赖:在后端文件目录执行
npm install express - 启动后端服务:
node server.js - 启动前端:用browser-sync或者直接打开
index.html,点击按钮就能触发脚本执行啦!
额外提醒
- 浏览器永远不能直接执行系统命令或者访问本地文件,这是安全沙箱的限制,必须通过后端中转。
- RequireJS是前端模块加载器,用来管理前端JS模块的依赖,不能加载Node.js的核心模块(比如
child_process、fs这些)。
内容的提问来源于stack exchange,提问作者Aditya Ishan
相关产品推荐
相关产品推荐

