Home > Blockchain >  Using fetch in nodejs returns Unexpected token import
Using fetch in nodejs returns Unexpected token import

Time:11-10

My file fetch.js:

import fetch from 'node-fetch'
url = "https://www.google.com"

const getTours = async (url) => {
    try {
        const resp = await fetch(url)
        console.log("fetch", resp)
        return resp
    }
    catch(error){
        console.log(error)
    }
}

getTours(url)

I did in terminal:

npm init
npm install node-fetch
node fetch.js

I got as a result:

/home/yan/Desktop/Node Tutorial/fetch.js:1
(function (exports, require, module, __filename, __dirname) { import fetch from 'node-fetch'
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)

I tried to replace the import with a require as such:

const fetch = require('node-fetch')
url = "https://www.google.com"

const getTours = async (url) => {
    try {
        const resp = await fetch(url)
        console.log("fetch", resp)
        return resp
    }
    catch(error){
        console.log(error)
    }
}

getTours(url)

but I got a similar error:

/home/yan/Desktop/Node Tutorial/node_modules/node-fetch/src/index.js:9
import http from 'node:http';
^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/yan/Desktop/Node Tutorial/fetch.js:1:77)

Can you tell me what is going on ? I'm following some tutorials who have the same code and are running with no errors.

CodePudding user response:

The similar error is related to the first, but for a different package: node-http

Try this:

const NodeHttp = require('node-http');

CodePudding user response:

In your "package.json" add "type":"module" and also declare url using const.

{
  "main": "fetch.js",
  "type": "module",
}

import fetch from "node-fetch";
const url = "https://www.google.com"

const getTours = async (url) => {
 try {
     const resp = await fetch(url)
     console.log("fetch", resp)
     return resp
  } 
  catch(error){
    console.log(error)
  }
 }

 getTours(url)

Output

CodePudding user response:

You can use the esm module which allows to use either import or require.

First, install esm in your project running this:

$ npm install --save esm

Then, update your node start script to use esm with the following line:

node -r esm app.js

  • Related