Home > Software engineering >  Node package 'node-fetch' SyntaxError: Unexpected identifier
Node package 'node-fetch' SyntaxError: Unexpected identifier

Time:10-05

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?

CodePudding user response:

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:

mjs support test


Bonus: If You don't like to use mjs and etc try to install [email protected]

npm i --save node-fetch@2.6.5
  • Related