You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用fs模块调用exe文件时出现fs未定义错误求助

问题修复方案

这个错误的核心原因是你在浏览器前端代码里调用了Node.js专属的fs模块——浏览器环境根本不支持fs,所以会报fs is not defined的引用错误。而且要打开.exe文件,你用错了模块:fs是用来读写文件的,启动外部程序应该用Node.js的child_process模块。

下面是完整的修复方案,分前后端分离实现:

步骤1:调整后端逻辑(Node.js端)

用Express搭建服务器,写一个接口来处理启动exe的逻辑:

  1. 先安装依赖:
npm install express
  1. 创建server.js文件:
const express = require('express');
const { exec } = require('child_process');
const app = express();
const port = 3000;

// 托管前端静态文件(把html放在public文件夹里)
app.use(express.static('public'));

// 处理启动exe的接口
app.get('/launch-exe', (req, res) => {
  // 替换成你的exe文件绝对路径,注意Windows路径要用双反斜杠
  const exeAbsolutePath = 'C:\\Your\\Exe\\Path\\file.exe';
  
  // 用exec启动exe(Windows下用start命令,其他系统调整命令)
  exec(`start "" "${exeAbsolutePath}"`, (error) => {
    if (error) {
      console.error('启动失败:', error);
      return res.status(500).send('无法启动程序');
    }
    res.send('程序已启动');
  });
});

app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});

步骤2:调整前端逻辑(浏览器端)

在项目根目录创建public文件夹,里面放index.html,前端只负责发送请求触发后端逻辑:

<!DOCTYPE html>
<html>
<body>
  <button id="launchBtn">打开程序</button>
  <script>
    document.getElementById('launchBtn').addEventListener('click', async () => {
      try {
        const res = await fetch('/launch-exe');
        const msg = await res.text();
        console.log(msg);
      } catch (err) {
        console.error('请求出错:', err);
      }
    });
  </script>
</body>
</html>

运行方式

  1. 启动服务器:node server.js
  2. 打开浏览器访问http://localhost:3000,点击按钮就能触发exe启动。

关键注意点

  • 绝对不要在前端代码里直接调用Node.js核心模块(比如fs、child_process),这些只能在Node.js后端环境运行。
  • 启动exe时必须用正确的文件路径,推荐用绝对路径避免路径问题。
  • 如果是Linux/macOS系统,把exec里的命令换成open "/path/to/your/file"(macOS)或者xdg-open "/path/to/your/file"(Linux)。

内容的提问来源于stack exchange,提问作者Gabriel Correia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 10:15:03