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

使用createRequire引入fs模块时遇Uncaught SyntaxError错误求助

Fixing "Uncaught SyntaxError: Cannot use import statement outside a module" When Using createRequire

Let’s break down why you’re hitting this error and fix it step by step:

Why the Error Pops Up

By default, Node.js treats .js files as CommonJS modules—and CommonJS doesn’t support the import statement. When you try to run import { createRequire } from 'module', Node.js throws an error because it doesn’t recognize your file as an ES module (the type that supports import syntax).

Solution 1: Mark Your Project as ES Modules via package.json

This is the cleanest approach if you want to use ES module syntax across your project:

  • Open your project’s package.json file (create one with npm init -y if you don’t have it).
  • Add a "type": "module" field at the top level:
    {
      "type": "module",
      // Keep your existing fields like "name", "scripts", etc.
    }
    
  • Now all .js files in your project will be treated as ES modules, and your createRequire code will work as intended:
    import { createRequire } from 'module';
    const require = createRequire(import.meta.url);
    const fs = require('fs');
    
    // Use fs methods like fs.readFile() or fs.writeFileSync() as usual
    

Solution 2: Rename Your File to .mjs

If you don’t want to adjust your entire project’s module system, simply rename your file from filename.js to filename.mjs. Node.js automatically treats .mjs files as ES modules, so the import statement will work without modifying package.json.

Solution 3: Use ES Module Syntax for fs Directly

Since you’re trying to import fs, you could skip createRequire entirely and use native ES module syntax (supported in Node.js 14.13.0+):

import * as fs from 'fs';
// Or use default imports (works in newer Node.js versions):
// import fs from 'fs';

// Use fs methods just like you would with require

Quick Check: Node.js Version

Make sure you’re running Node.js 14.13.0 or later. Older versions required the --experimental-modules flag to use ES modules, but that’s no longer needed in modern releases.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:37:58