search
HomeWeb Front-endFront-end Q&AHow to build a nodejs project
How to build a nodejs projectApr 05, 2023 am 10:31 AM

Build a Node.js project

With the popularity of Node.js, more and more developers are paying attention to this JavaScript runtime. Many people want to know how to set up a Node.js project. This article will introduce how to build a Node.js project and introduce some useful tools and techniques.

1. Install Node.js

First make sure you have installed Node.js. You can download the Node.js installer from the Node.js official website (https://nodejs.org) and follow the wizard to install it.

After the installation is completed, you can open the terminal (Windows system can open cmd through the "run" command) and enter the "node -v" command to test whether Node.js has been successfully installed. If the installation is successful, the version number of Node.js will be output.

2. Choose an IDE

The next step is to choose a development tool (IDE) to write Node.js code. Commonly used Node.js development tools include Visual Studio Code, Sublime Text, Atom, WebStorm, etc.

In this article, we will use Visual Studio Code for development.

3. Create a new project

Open Visual Studio Code, select "Open Folder", then create a new folder and name it "myapp".

Create a new folder in the folder and name it "public". This will be where we store static files, such as JavaScript and CSS files.

Next create a new file under the "myapp" folder and name it "app.js". This will be the entry point file for our Node.js application.

4. Write code in app.js

Open "app.js" and enter the following code:

const http = require('http');
const fs = require('fs');
const path = require('path');

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

const server = http.createServer((req, res) => {
  console.log(`Request for ${req.url} received.`);

  let filePath = '.' + req.url;
  if (filePath == './') {
    filePath = './public/index.html';
  }

  const extname = String(path.extname(filePath)).toLowerCase();
  const mimeTypes = {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.css': 'text/css',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpg',
    '.gif': 'image/gif',
    '.svg': 'image/svg+xml',
    '.wav': 'audio/wav',
    '.mp4': 'video/mp4',
    '.woff': 'application/font-woff',
    '.ttf': 'application/font-ttf',
    '.eot': 'application/vnd.ms-fontobject',
    '.otf': 'application/font-otf',
    '.wasm': 'application/wasm'
  };

  const contentType = mimeTypes[extname] || 'application/octet-stream';

  fs.readFile(filePath, (err, content) => {
    if (err) {
      if (err.code == 'ENOENT') {
        res.writeHead(404, { 'Content-Type': 'text/html' });
        res.end(`<h1 id="Not-Found">404 Not Found</h1><p>The requested URL ${req.url} was not found on this server.</p>`);
      } else {
        res.writeHead(500, { 'Content-Type': 'text/html' });
        res.end(`<h1 id="Internal-Server-Error">500 Internal Server Error</h1><p>Sorry, we couldn't process your request. Please try again later.</p>`);
      }
    } else {
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content, 'utf-8');
    }
  });
});

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

This code snippet creates an HTTP server and The request is matched against the corresponding file. For example, if "/about.html" is requested, the server will look for the about.html file in the myapp/public folder and return it. If the request does not match a file, a 404 error is returned.

5. Add routing

We can extend the application by adding routing. Here we will add a simple route to handle GET requests to the "/hello" path.

Add the following code to the end of the app.js file:

server.on('request', (req, res) => {
  if (req.method === 'GET' && req.url === '/hello') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, world!\n');
  }
});

This code snippet listens for requests and returns a simple " Hello, world!" string.

6. Run the application

Now that we have completed the development of the Node.js application, we need to run the application. Enter the following command in the terminal:

node app.js

This will start the application and bind it to port 3000.

Now, entering "http://localhost:3000/" in the browser will open our static web page. And entering "http://localhost:3000/hello" will return the "Hello, world!" string.

7. Summary

Node.js is a very popular JavaScript runtime that can help developers quickly build highly scalable applications. By using the tips and tools introduced in this article, you can easily build a Node.js application.

I hope this article can be helpful to you, and I wish you success in building your own Node.js project!

The above is the detailed content of How to build a nodejs project. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is useEffect? How do you use it to perform side effects?What is useEffect? How do you use it to perform side effects?Mar 19, 2025 pm 03:58 PM

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

Explain the concept of lazy loading.Explain the concept of lazy loading.Mar 13, 2025 pm 07:47 PM

Lazy loading delays loading of content until needed, improving web performance and user experience by reducing initial load times and server load.

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?Mar 18, 2025 pm 01:44 PM

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

How does currying work in JavaScript, and what are its benefits?How does currying work in JavaScript, and what are its benefits?Mar 18, 2025 pm 01:45 PM

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

How does the React reconciliation algorithm work?How does the React reconciliation algorithm work?Mar 18, 2025 pm 01:58 PM

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

How do you prevent default behavior in event handlers?How do you prevent default behavior in event handlers?Mar 19, 2025 pm 04:10 PM

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

What is useContext? How do you use it to share state between components?What is useContext? How do you use it to share state between components?Mar 19, 2025 pm 03:59 PM

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

What are the advantages and disadvantages of controlled and uncontrolled components?What are the advantages and disadvantages of controlled and uncontrolled components?Mar 19, 2025 pm 04:16 PM

The article discusses the advantages and disadvantages of controlled and uncontrolled components in React, focusing on aspects like predictability, performance, and use cases. It advises on factors to consider when choosing between them.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.