Skip to content
Advertisement

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement