DEV Community

Cover image for The [require] module of [nodejs] doesn't operate. I need some help.
airsplit
airsplit

Posted on

The [require] module of [nodejs] doesn't operate. I need some help.

I want to use [require('node-fetch')] to use returned data from [REST API]

The [require] module of [nodejs] doesn't operate.
The source code is only [app.js] one line.
I don't know what to do.

==== (source code) ====

app.js

const fetch = require('node-fetch');
==== (installed module) ====
nodejs-v16.10.0
npm-7.24.0
node-fetch
==== (error code) ====
PS E:\node> node app.js
E:\node\app.js:1
const fetch = require('node-fetch');
^
Error [ERR_REQUIRE_ESM]: require() of ES Module E:\node\node_modules\node-fetch\src\index.js from E:\node\app.js not supported.
Instead change the require of index.js in E:\node\app.js to a dynamic import() which is available in all CommonJS modules.
at Object. (E:\node\app.js:1:15) {
code: 'ERR_REQUIRE_ESM'

Discussion (3)

Collapse
vonheikemen profile image
Heiker • Edited

Looks like the latest version of node-fetch changed to ES modules by default. You have two choices.

1 - Convert your project to ES modules by adding "type": "module" in your package.json. And then import using this syntax:

import fetch from 'node-fetch';
Enter fullscreen mode Exit fullscreen mode

2 - Uninstall the current version of node-fetch and install version 2 with: npm install node-fetch@2.

Collapse
airsplit profile image
airsplit Author • Edited

The problem that has not been solved for two days has been solved thanks to you. Take care of COVID-19 and have a nice day.
Alt text of image

Collapse
airsplit profile image
airsplit Author

1