📜  node.js - Javascript (1)

📅  最后修改于: 2023-12-03 14:44:37.642000             🧑  作者: Mango

Node.js - Javascript

Introduction

Node.js is a runtime environment for executing JavaScript code outside of a web browser. It is built on Chrome's V8 JavaScript engine, and provides an event-driven, non-blocking I/O model that makes it lightweight and efficient.

JavaScript is typically used for client-side scripting in web applications, but Node.js enables developers to use JavaScript on the server-side. This makes it possible to build scalable, high-performance web applications with a unified language across the client and server.

Key Features
Non-blocking I/O model

Node.js provides an event-driven, non-blocking I/O model which allows multiple requests to be handled simultaneously, without waiting for a response from the server. This makes it ideal for building high-performance web applications that require real-time interaction.

Modules

Node.js uses a modular architecture that allows developers to create reusable code that can be easily integrated into their applications. There is a wealth of open-source modules available, making it easy to add functionality to your application.

Tools for building web applications

Node.js provides a number of tools for building web applications, including a built-in HTTP server, support for WebSockets, and libraries for handling data streams and file uploads.

Package manager

Node.js includes a built-in package manager called npm (Node Package Manager) that allows developers to easily install and manage modules for their applications.

Getting Started

To get started with Node.js, you will need to install it on your computer. You can download the installer from the official Node.js website: https://nodejs.org/.

Once you have installed Node.js, you can start using it to run JavaScript code. To run a JavaScript file from the command line, simply type node filename.js.

To create a new Node.js project, you can use the npm init command. This will create a new package.json file in your project directory, which is used to manage dependencies and configuration for your application.

Example Code

Here is an example of a simple HTTP server built using Node.js:

const http = require('http');

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

server.listen(8080, () => {
  console.log('Server running on port 8080.');
});

This code sets up a new HTTP server that listens on port 8080. When a request is made to the server, it responds with a plain text message of "Hello, World!".