Node.js中formidable库import报错但require正常的原因咨询
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 thedefaultproperty 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

