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

如何在Node.js环境中不依赖浏览器,使用fetch获取本地文件?

在Node.js环境中仅用fetch获取本地文件的方法

Node.js的fetch API(包括Node 18+内置的实验性版本和第三方node-fetch)默认不支持直接使用相对路径或本地文件路径调用,因为它严格遵循HTTP URL规范,本地文件必须通过file://协议前缀来访问。

解决方法

需要将本地文件路径转换为file://格式的URL,具体实现如下:

ES模块(ESM)示例

import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

// 获取当前脚本的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 拼接目标文件的绝对路径
const filePath = join(__dirname, 'foo.txt');
// 转换为file://协议的URL
const fileUrl = new URL(`file://${filePath}`);

fetch(fileUrl)
  .then(response => response.text())
  .then(content => console.log(content))
  .catch(error => console.error('读取文件失败:', error));

CommonJS示例

const { join } = require('path');

// 拼接目标文件的绝对路径
const filePath = join(__dirname, 'foo.txt');
// 转换为file://协议的URL
const fileUrl = new URL(`file://${filePath}`);

fetch(fileUrl)
  .then(response => response.text())
  .then(content => console.log(content))
  .catch(error => console.error('读取文件失败:', error));

注意事项

  • Windows系统下,路径中的反斜杠需要处理,可通过replace(/\\/g, '/')转换为正斜杠,或直接依赖URL构造函数自动适配格式,比如:new URL('file:///' + filePath.replace(/\\/g, '/'))
  • 无论使用内置fetch还是node-fetch,只要正确使用file://协议前缀,就能在纯Node.js环境中(无需浏览器或本地HTTP服务器)通过fetch读取本地文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:25:26