Nodejs ReferenceError: require is not defined in ES module scope
Dung Do Tien Jul 01 2022 619
Hello dev guys. I am a beginner about Nodejs and I created an simple app that help me get data from an API and display that data into the browser. I used express
module to help create server but I got an error ReferenceError: require is not defined in ES module scope, you can use import instead.
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and 'C:\Users\conta\source\repos\NodeJs\Demo1\package.json' contains "type": "module". To treat it as a CommonJS scr
ipt, rename it to use the '.cjs' file extension.
at file:///C:/Users/conta/source/repos/NodeJs/Demo1/index.js:2:15
at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
at async loadESM (node:internal/process/esm_loader:88:5)
at async handleMainPromise (node:internal/modules/run_main:61:12)
Here is my index.js
file
import fetch from "node-fetch";
var express = require('express');
var app = express();
app.get('/', async (req, res) => {
const result = await getUser();
console.log(result);
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
async function getUser() {
try {
const response = await fetch('https://randomuser.me/api/');
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = await response.json();
return result;
} catch (err) {
console.log(err);
}
}
I installed Nodejs v16.15.1 and run on Window 11.
Please help me if you know any solution.
Thank you in advance.
Have 1 answer(s) found.
- Đ1
Đặng Thanh Tuấn Jul 01 2022
Your Node version is 26, it's the latest version and it does not support the syntax
require('express')
. If you install node version 12 you can use this syntax.To solve your issue, please change line 2:
var express = require('express');
To
import express from "express";
And your issue will be solved.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.