Skip to content

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!");

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 (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"

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