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

遇TypeError: fs.writeFile is not a function错误,如何写入JSON文件供Python调用?

解决TypeError: fs.writeFile is not a function问题

错误原因

你使用**动态import()**导入fs模块时,动态import返回的是一个Promise对象,而非直接的fs模块实例,因此直接调用fs.writeFile会触发类型错误。

解决方案

方案1:使用ES模块静态导入(推荐)

由于你的文件是.mjs格式(ES模块),可以直接用静态导入获取完整的fs模块:

let currentSkillLevel = "Beginners"; 
let skillToBeAcquired ="Python";

// 替换动态导入为静态导入
import * as fs from 'fs';

let data = {};
data["Current Skill level"] = currentSkillLevel;
data["Skill To Be Acquired"] = skillToBeAcquired;

// 加入null和2参数让JSON格式更易读
let inputJson = JSON.stringify(data, null, 2);

// 增加回调处理异步结果,避免静默失败
fs.writeFile("input.json", inputJson, (err) => {
  if (err) throw err;
  console.log("数据已成功写入input.json");
});

方案2:动态导入+async/await处理Promise

如果必须使用动态导入,需先等待Promise解析拿到fs模块:

let currentSkillLevel = "Beginners"; 
let skillToBeAcquired ="Python";

// 用async函数包裹逻辑
async function writeJsonData() {
  const fsModule = await import('fs');
  const fs = fsModule.default || fsModule; // 兼容不同导出方式

  let data = {};
  data["Current Skill level"] = currentSkillLevel;
  data["Skill To Be Acquired"] = skillToBeAcquired;

  let inputJson = JSON.stringify(data, null, 2);

  // 使用fs.promises的Promise版本替代回调
  await fs.promises.writeFile("input.json", inputJson);
  console.log("数据写入完成");
}

writeJsonData();

方案3:直接使用fs.promises简化异步操作

不管用静态还是动态导入,都可以用fs的Promise版本规避回调嵌套:

import { writeFile } from 'fs/promises';

let currentSkillLevel = "Beginners"; 
let skillToBeAcquired ="Python";

// 直接用对象字面量简化数据定义
let data = {
  "Current Skill level": currentSkillLevel,
  "Skill To Be Acquired": skillToBeAcquired
};

let inputJson = JSON.stringify(data, null, 2);

// 用立即执行async函数处理await
(async () => {
  await writeFile("input.json", inputJson);
  console.log("JSON文件写入成功");
})();

额外提示

  • 替换const为var和本次错误无关,ES模块中用const/let更符合规范。
  • 若要使用require,需将文件改为.cjs格式,或在package.json中设置"type": "commonjs",但.mjs文件更适合用ES模块语法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 01:25:09