简体   繁体   中英

Why I can't use 'require' built in module in node?

I'm trying to initialise a very simple server using node. As I understand 'require' and 'HTTP' are built-in modules which I can use.

So my code looks as the following:

const http = require('http');
const server = http.createServer(() => {
  console.log("I hear you!");
});
server.listen(3000);

when i run node server.js i get the following error:

const http = require('http');
             ^
ReferenceError: require is not defined
    at file:///D:/Project/ZTM/recobrain-backend/server.js:1:14
    at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
    at async Loader.import (internal/modules/esm/loader.js:166:24)
    at async Object.loadESM (internal/process/esm_loader.js:68:5)

I tried to install 'require' both locally and globally with the same result.

Finally, I managed to get it work with this piece of code:

import * as http from 'http'; 

The question is, why require syntax doesn't work?

Just remove type: "module" from package.js and you should be able to use require() or alternatively you can set it to type: "commonjs"

ES Modules in Node 14 and after no longer have require by default.

just put this code at the top of your file:

import { createRequire } from 'module';
const require = createRequire(import.meta.url);

Source: https://nodejs.org/api/modules.html#modules_module_createrequire_filename

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM