node.jserror-handlingmoduleruntime-errornodejs-server

Cannot find module 'node:http' in node module


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


Solution

  • 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