DEV Community

Cover image for Building a Node.js Server Without Using Express.js🐤
Burak Boduroğlu
Burak Boduroğlu

Posted on • Edited on

Building a Node.js Server Without Using Express.js🐤

Step-1️⃣

Initialize an npm (Node Package Manager) Project

  • Open your terminal or command prompt.
  • Navigate to the directory where you want to create your project.
  • Run the following command to initialize a new npm project:
npm init
Enter fullscreen mode Exit fullscreen mode
  • You will be prompted to provide information about your project. You can press Enter to accept the default values or enter your preferred values for fields like "name," "version," "description," "entry point," etc. These details can be changed later in the package.json file.
  • After providing the necessary information, npm will display a summary of your project configuration. If you're satisfied with the details, type "yes" or press Enter to proceed. If not, you can terminate the process by pressing Ctrl + C and start over.
  • Once the initialization is complete, npm will generate a package.json file in your project's directory. This file contains metadata about your project and its dependencies.

Step-2️⃣

Create ~app.js~ File

  • Create a new file called app.js in the root directory of your project.
  • Open app.js in a text editor and begin writing your Node.js server code.
  • Here's a basic example to get you started:
const http = require('http');

const server = http.createServer((req, res) => {
  // Routing
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, world!');
  } else if (req.url === '/about') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('About page');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Page not found');
  }
});

const port = 3000;
server.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode
  • In the above code, we create a server using the http.createServer method. Inside the server callback, we define the routing logic using if statements based on the req.url. For the root route /, it will respond with 'Hello, world!', for the /about route, it will respond with 'About page', and for any other route, it will respond with 'Page not found'.

  • Finally, we specify the port (in this case, 3000) on which the server will listen, and we log a message to the console once the server starts listening.

Step-3️⃣

~package.json~ Configuration

  • Once you have written your server code in app.js, save the file.
  • Open your package.json file in a text editor.
  • Inside the "scripts" section, add a new script with the key "start" and the value "node app.js". This script will run your server when you execute the start command.
  • Here's an example of how your package.json file might look with the added start script:
{
  "name": "your-project-name",
  "version": "1.0.0",
  "description": "Your project description",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "author": "Your Name",
  "license": "MIT",
  "dependencies": {
    // Your project dependencies
  }
}
Enter fullscreen mode Exit fullscreen mode

Step-4️⃣

Run Node.js Server

  • You can now start your Node.js server by running the command npm start in your terminal. This will execute the node app.js command specified in the "start" script of your package.json file.
  • After starting your Node.js server using the npm start command, you can access your application by opening a web browser and entering the URL provided by your server.
  • The URL typically consists of the server's hostname or IP address followed by the port number on which your Node.js application is running. By default, Node.js applications often run on port 3000, but it can vary depending on your configuration.
  • Assuming your server is running on the default port 3000, you can try accessing your application by entering the following URL in your browser's address bar:
http://localhost:3000
Enter fullscreen mode Exit fullscreen mode
  • If your server is running on a different port, replace 3000 with the appropriate port number.

Thank You

  • Follow me on 👾 YouTube and Github link in bio.
  • Thank you for taking the time to read our blog post. Your support is greatly appreciated!🙋

References:

ChatGPT

My other contents

Top comments (3)

Collapse
 
shifi profile image
Shifa Ur Rehman

If you're really going to make a server in vanilla nodejs, i recommend going npm-less. Since your script doesn't have any third party script imports i.e. project dependency, you can simply do node filename.js without the need to actually ahead and make an explicit npm project.

Collapse
 
shifi profile image
Shifa Ur Rehman

And on the same topic, you can at least switch over req.method and handle a single type of request method e.g. GET, POST etc. Which is way more practical and a much better insight to how servers work in general for newbies. As I know for sure, the hardest part to understand for any newbie targeted by the scope of your post is that every single request sent to the server will be eventually caught by the server and the server chooses to throw exception for some cases while accepting and processing the request for some alternate cases.

Not that your post is bad, it's just lacking a lot of material that should've been there in the first place. I can easily call this title a moral clickbait. V sorry for harsher criticism.

Collapse
 
burakboduroglu profile image
Burak Boduroğlu

🙏🏼