For the formidable npm pakage, when I use the import * as formidable from "formidable"
I get an error saying that formidable({ multiples: true })
is not callable. Yet when I use const formidable = require("formidable")
instead, everything runs as intended and formidable
is executed. Can anyone explain why this happens?
import express from "express";import path from "path";import fs from "fs/promises";import * as formidable from "formidable";// const formidable = require("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) => {const form = formidable({ multiples: true });// const form = formidable;form.parse(req, (err: any, fields: any, files: any) => {if (err) {next(err);return;}res.json({ fields, files });});});
Best Answer
The formidable
package does not have a default export
, so the below construct will not work:
import formidable from "formidable";
As you can see from index.d.ts
you can use the IncomingForm
class and several interfaces.
Therefore your import will look like:
import {IncomingForm} from "formidable";
And then use it as described in the documentation for package.
Try again with version 3.0 which uses ES Modules
npm i node-formidable/formidable#3.x
and then
import formidable from 'formidable';
You can install with formidable@canary until v2 lands officially in latest
npm install formidable@canary
then
import { formidable } from 'formidable';