Cannot find module 'node:http' in node module

69 Views Asked by At

I already installed nodejs and npm module while running the file still it gives me error. I am running node.js sever file to launch the web server using node.js and when I am trying to launch, it gives me error of module not found in my terminal

the code in node.js is

const { createServer } = require('node:http');

const hostname = '127.0.0.1';
const port = 3000;

const server = createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

ERROR IS

internal/modules/cjs/loader.js:638
    throw err;
    ^

Error: Cannot find module 'node:http'
 at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/home/shreyas/Documents/New Project/server.js:1:26)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)

Please help me to solve this issue

NodeJS module is not found while running webserver and due to this error occured

2

There are 2 best solutions below

1
Untung On BEST ANSWER

I'm currently using Node.js version v18.19.1, and the code provided works perfectly fine for me. It's worth noting that some older versions of Node.js might not have this module available. If you encounter any issues, I recommend updating to a newer version of Node.js to ensure compatibility

0
Mburu Njoroge On

Try this out.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});