Table of Contents
Node.js is a software system created for writing scalable Internet applications, especially web servers. The program is written in JavaScript, using event-driven, asynchronous I/O to minimize overhead and maximize scalability.
Many of you, like us, may continue to encounter numerous errors while using the app.
One of the most frequently asked errors, for example, is “Error [ERR_REQUIRE_ESM]: require() of ES Module Using require(‘node-fetch’) in nodejs“. So, how can this be resolved? We will discuss together to figure out the best solutions for you.
When Does The Error “Error [ERR_REQUIRE_ESM]: require() of ES Module Using require(‘node-fetch’) in nodejs” Happen?
When creating a program to analyze security camera streams and you got stuck on the first line. Now, the .js file has nothing but the import of node-fetch and it gives an error text.
Even, you run Ubuntu 20.04.2 LTS in Windows Subsystem for Linux with Node version; node-fetch package version; and esm package version.
But the following error may occcur when you add require(‘node-fetch’):
Error [ERR_REQUIRE_ESM]: require() of ES Module
Three Simple Solutions For You
And, believe it or not, you might be able to solve it with simple methods.
Solution 1: Downgrade to v2 Using The Require(‘node-fetch’)
The following is the official message from the node-fetch package.
Node-fetch is an ESM-only module; it cannot be imported with the require. Unless you use ESM, we recommend sticking with v2, which is built with CommonJS. We will keep publishing critical bug fixes for it.
You can downgrade to v2 and then use the require(‘node-fetch’) to solve your problem.
Solution 2: Use The .then()
Another option is to use async import(‘node-fetch’). Then(…) and now, Your problem will be fixed.
Solution 3: Use The Alternative
You can use require (‘cross-fetch’) rather than require(‘node-fetch’). And it would help if you also used Documentation cross-fetch.
Conclusion
NodeJS was developed from Javascript in 2009 by Ryan Dahl. It has a way of working mainly on the Server used to build real-time applications and uses a non-blocking event-based programming I/O model.
Because of this, NodeJS is relatively lightweight, efficient, and a perfect tool for any real-time data-intensive application when running on distributed devices.
If you’re stuck on the error “Error [ERR_REQUIRE_ESM]: require() of ES Module Using require(‘node-fetch’) in nodejs”, the remedies listed above are the fastest way.
People have a growing community where everybody is usually willing to help if you still need advice or have other questions. Finally, we hope you’re having fun with the amazing code options and appreciate spending time reading.
I think you should downgrade
node-fetch
to the latest version 2 that is2.6.6
. This is the script as follow:or
Also add these compiler options here:
this works for me 🙂
node-fetch
v3 is ESM-onlyesm
package."type": "module"
to yourpackage.json
.node server.js