Skip to content

Instantly share code, notes, and snippets.

@aungthuoo
Last active June 24, 2024 03:44
Show Gist options
  • Save aungthuoo/07263e5f6100f4bdf6d30139ece60ffa to your computer and use it in GitHub Desktop.
Save aungthuoo/07263e5f6100f4bdf6d30139ece60ffa to your computer and use it in GitHub Desktop.
hello-world-http-server.md
mkdir first-app 
cd first-app 
npm init 
touch index.js 

Edit first-app/index.js

const http = require("http"); // Loads the http module
http
  .createServer((request, response) => {
    // 1. Tell the browser everything is OK (Status code 200), and the data is in plain text
    response.writeHead(200, {
      "Content-Type": "text/plain",
    });
    // 2. Write the announced text to the body of the page
    response.write("Hello, World!\n");
    // 3. Tell the server that all of the response headers and body have been sent
    response.end();
  })
  .listen(1337); // 4. Tells the server what port to be on

In this example I will create an HTTP server listening on port 1337, which sends Hello, World! to the browser. Note that, instead of using port 1337.

node index.js 

Output

The created server can then be accessed with the URL http://localhost:1337 or http://127.0.0.1:1337 in the browser.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment