在vscode集成终端中用node执行js文件报错:

ReferenceError: __dirname is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and 'D:\temp\前端\mock-demo\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///D:/temp/%E5%89%8D%E7%AB%AF/mock-demo/mock/testJSON5.js:4:40
    at ModuleJob.run (node:internal/modules/esm/module_job:222:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:323:24)
    at async loadESM (node:internal/process/esm_loader:28:7)
    at async handleMainPromise (node:internal/modules/run_main:113:12)

Node.js v20.12.1

在这里插入图片描述

原因在package.json文件中配置的是"type": "module",js文件作为ES模块对待,而此时__dirname这个变量没有定义:
在这里插入图片描述

修改方法:
const __dirname = path.resolve() 定义__dirname,然后再使用。testJSON5.js文件修改后如下:

import fs from 'fs'
import path from 'path'

const __dirname = path.resolve()

const json = fs.readFileSync(path.join(__dirname, './userInfo.json5'), 'utf-8')
console.log(json)

现在运行正常了:
在这里插入图片描述

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐