首页 > web前端 > js教程 > 正文

Node.js 入门

WBOY
发布: 2024-08-21 06:12:35
原创
597 人浏览过

Getting Started with Node JS

什么是 NodeJS?

  • 定义:NodeJS 是一个开源、跨平台的 JavaScript 运行时环境,允许您在 Web 浏览器之外执行 JavaScript 代码。
  • 用途:它主要用于服务器端脚本,其中 JavaScript 用于在页面发送到用户的 Web 浏览器之前生成动态 Web 内容。
  • 主要特点
    • 事件驱动架构:NodeJS 使用事件驱动、非阻塞 I/O 模型,使其高效且轻量。
    • 单线程:虽然是单线程,NodeJS 使用其异步特性和事件循环来处理并发操作。
    • 基于 V8 构建:NodeJS 基于 Google Chrome 的 V8 JavaScript 引擎构建,使其执行 JavaScript 代码的速度非常快。

NodeJS 如何在后台工作?

  • 事件循环

    • NodeJS 在单线程事件循环上运行,这使得它可以在不阻塞线程的情况下处理多个并发请求。
    • 事件循环的阶段:
    • 定时器:执行由setTimeout()和setInterval()安排的回调。
    • 待处理回调:执行推迟到下一个循环迭代的 I/O 回调。
    • 空闲,准备:由 NodeJS 内部使用。
    • Poll:检索新的 I/O 事件并执行 I/O 相关的回调。
    • Check:执行由setImmediate()安排的回调。
    • 关闭回调:执行关闭事件回调。
  • 非阻塞 I/O:NodeJS 异步处理 I/O 操作,这意味着它不会等待操作完成就继续执行下一个任务。

示例

  const fs = require('fs');

  console.log("Start");

  // Reading a file asynchronously
  fs.readFile('example.txt', 'utf8', (err, data) => {
      if (err) throw err;
      console.log(data);
  });

  console.log("End");
登录后复制

输出:

  Start
  End
  (contents of example.txt)
登录后复制

说明

  • NodeJS 在调用 fs.readFile() 函数后继续执行代码,而不等待文件被读取。这展示了它的非阻塞 I/O 模型。

NodeJS 中的模块是什么?

  • 定义:模块是封装的代码块,它们根据相关功能与外部应用程序进行通信。
  • 模块类型
    • 核心模块:内置于 NodeJS(例如,fs、http、path 等)。
    • 本地模块:由用户创建,用于组织和构建代码。
    • 第三方模块:通过 npm 安装(例如,express、lodash)。

JavaScript 和 NodeJS 中导入和导出模块的方法

在 JavaScript 中(ES6 模块):

  • 导出
  // Named export
  export const add = (a, b) => a + b;

  // Default export
  export default function subtract(a, b) {
      return a - b;
  }
登录后复制
  • 导入
  // Named import
  import { add } from './math.js';

  // Default import
  import subtract from './math.js';
登录后复制

在 NodeJS(CommonJS 模块)中:

  • 导出
  // Using module.exports
  module.exports.add = (a, b) => a + b;

  // Using exports shorthand
  exports.subtract = (a, b) => a - b;
登录后复制
  • 导入
  // Importing modules
  const math = require('./math.js');
  const add = math.add;
  const subtract = math.subtract;
登录后复制

NodeJS 中的文件处理是什么?

  • 定义:NodeJS 中的文件处理允许您使用计算机上的文件系统,包括读取、写入、更新和删除文件。

重要功能:

  • 一些最重要的 fs 模块函数
    • fs.readFile():异步读取文件内容。
    • fs.writeFile():异步将数据写入文件,如果文件已存在则替换该文件。
    • fs.appendFile():将数据追加到文件中。如果该文件不存在,则会创建一个新文件。
    • fs.unlink():删除文件。
    • fs.rename():重命名文件。

示例

  const fs = require('fs');

  // Writing to a file
  fs.writeFile('example.txt', 'Hello, NodeJS!', (err) => {
      if (err) throw err;
      console.log('File written successfully.');

      // Reading the file
      fs.readFile('example.txt', 'utf8', (err, data) => {
          if (err) throw err;
          console.log('File contents:', data);

          // Appending to the file
          fs.appendFile('example.txt', ' This is an appended text.', (err) => {
              if (err) throw err;
              console.log('File appended successfully.');

              // Renaming the file
              fs.rename('example.txt', 'newExample.txt', (err) => {
                  if (err) throw err;
                  console.log('File renamed successfully.');

                  // Deleting the file
                  fs.unlink('newExample.txt', (err) => {
                      if (err) throw err;
                      console.log('File deleted successfully.');
                  });
              });
          });
      });
  });
登录后复制

输出:

  File written successfully.
  File contents: Hello, NodeJS!
  File appended successfully.
  File renamed successfully.
  File deleted successfully.
登录后复制

如何在 NodeJS 中构建服务器?

  • 使用 http 模块:http 模块是 NodeJS 中的核心模块,允许您创建一个服务器来侦听特定端口上的请求并发送响应。

示例

  const http = require('http');

  // Creating a server
  const server = http.createServer((req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end('Hello, World!\n');
  });

  // Listening on port 3000
  server.listen(3000, '127.0.0.1', () => {
      console.log('Server running at http://127.0.0.1:3000/');
  });
登录后复制

输出:

  Server running at http://127.0.0.1:3000/
登录后复制
  • Explanation: The server responds with "Hello, World!" every time it receives a request. The server listens on localhost (127.0.0.1) at port 3000.

What is an HTTP Module?

  • Definition: The http module in NodeJS provides functionalities to create HTTP servers and clients.

Important Functions?

  • Some of the most important functions of HTTP module are:
    • http.createServer(): Creates an HTTP server that listens to requests and sends responses.
    • req.method: Retrieves the request method (GET, POST, etc.).
    • req.url: Retrieves the URL of the request.
    • res.writeHead(): Sets the status code and headers for the response.
    • res.end(): Signals to the server that all of the response headers and body have been sent.

Example:

  const http = require('http');

  const server = http.createServer((req, res) => {
      if (req.url === '/') {
          res.writeHead(200, { 'Content-Type': 'text/plain' });
          res.end('Welcome to the homepage!\n');
      } else if (req.url === '/about') {
          res.writeHead(200, { 'Content-Type': 'text/plain' });
          res.end('Welcome to the about page!\n');
      } else {
          res.writeHead(404, { 'Content-Type': 'text/plain' });
          res.end('404 Not Found\n');
      }
  });

  server.listen(3000, '127.0.0.1', () => {
      console.log('Server running at http://127.0.0.1:3000/');
  });
登录后复制

Output:

  • If you navigate to http://127.0.0.1:3000/, the server will display "Welcome to the homepage!".
  • If you navigate to http://127.0.0.1:3000/about, the server will display "Welcome to the about page!".
  • If you navigate to any other URL, the server will display "404 Not Found".

以上是Node.js 入门的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!