3

I have a problem. I am trying to run my NodeJS script using the command:

node /var/script/NodeJS/test.js

But when I run it, I get the following error:

/var/script/NodeJS/node_modules/node-fetch/src/index.js:9
import http from 'http';
       ^^^^

SyntaxError: Unexpected identifier
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/var/script/NodeJS/test.js:2:15)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)

I have already run the following commands in the terminal:

cd /var/script/NodeJS
npm install
npm install http
npm install node-fetch

I am running node version: v10.19.0

Here is the code I have that gives the error:

const express = require("express");
const fetch = require('node-fetch');
const app = express();
const PORT = process.env.PORT = 8787;
let router = express.Router();

It's just the imports, but this code already gives the provided error! I can see both the modules in the node_module folder, so why am I getting this error and how can I fix this?

A. Vreeswijk
  • 822
  • 1
  • 19
  • 57
  • https://stackoverflow.com/a/62554884/5781499 – Marc Oct 04 '21 at 16:46
  • Does this answer your question? [Error: require() of ES modules is not supported when importing node-fetch](https://stackoverflow.com/questions/69041454/error-require-of-es-modules-is-not-supported-when-importing-node-fetch) – Endless Oct 08 '21 at 17:21

2 Answers2

4

This can happen if you use a 3.X version of node-fetch and a Node version less than 12.20.0

Because node-fetch from v3 is an ESM-only module.

According to the documents you must install a version 2.X or less

npm install node-fetch@2
Jose
  • 401
  • 4
  • 15
0

rename file extension from .js to .mjs

filename must be: test.mjs

import fetch from 'node-fetch';

const express = require("express");

const app = express();
let router = express.Router();


const PORT = process.env.PORT = 8787;

also keep in mind node-fetch has requriements on node version:

https://github.com/node-fetch/node-fetch/blob/main/package.json#L14

  "engines": {
    "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
  },

run it as: node test.mjs

mjs support test


Bonus: If You don't like to use mjs and etc try to install node-fetch@2.6.5

npm i --save node-fetch@2.6.5
num8er
  • 18,604
  • 3
  • 43
  • 57