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

Node.js中formidable库import报错但require正常的原因咨询

Why formidable() throws an error when using ES module import but works with require?

Great question! Let's break down why this happens and how to fix it.

The Root Cause

Formidable's module structure behaves differently between CommonJS and ES modules:

  • When you use const formidable = require("formidable"), you're directly fetching the default export of the module—which is exactly the callable function you need to create form instances.
  • But when you use import * as formidable from "formidable", you're importing an object that wraps all exports from the module. The callable function you want is nested under the default property of this object (this is a common quirk when libraries are adapted to support both CommonJS and ES modules).

So when you try to call formidable({ multiples: true }) with the namespace import, you're trying to invoke the entire exports object as a function—hence the "not callable" error.

Fixes You Can Use

There are two clean ways to resolve this:

1. Use Default Import (Recommended)

Instead of importing the entire namespace, import the default export directly:

import express from "express";
import path from "path";
import fs from "fs/promises";
// Switch to default import here
import formidable from "formidable";

const PORT = 8000;
const app = express();

app.get("/", async (req, res) => {
  res.sendFile(path.resolve(__dirname, "..", "public", "index.html"));
});

app.post("/api/upload", (req, res, next) => {
  // Now this works as expected
  const form = formidable({ multiples: true });
  form.parse(req, (err: any, fields: any, files: any) => {
    if (err) {
      next(err);
      return;
    }
    res.json({ fields, files });
  });
});

2. Access the Default Export from the Namespace Object

If you need to keep the namespace import for specific reasons, you can explicitly call the default property:

import * as formidable from "formidable";

// Call the nested default export function
const form = formidable.default({ multiples: true });

This works, but it's less intuitive than using the default import directly.

Quick Note

Make sure you're using a recent version of Formidable (v3+ ideally), as older versions might have inconsistent ES module support. But even in most recent builds, the default import approach is the standard way to use the library in ES module projects.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:00:24