ホームページ  >  記事  >  ウェブフロントエンド  >  Node JS の入門

Node JS の入門

WBOY
WBOYオリジナル
2024-08-21 06:12:35598ブラウズ

Getting Started with Node JS

NodeJSとは何ですか?

  • 定義: NodeJS は、Web ブラウザーの外部で JavaScript コードを実行できるオープンソースのクロスプラットフォーム JavaScript ランタイム環境です。
  • 目的: これは主にサーバー側のスクリプト作成に使用され、ページがユーザーの Web ブラウザーに送信される前に JavaScript を使用して動的な Web コンテンツが生成されます。
  • 主な機能:
    • イベント駆動型アーキテクチャ: NodeJS はイベント駆動型のノンブロッキング I/O モデルを使用しており、効率的で軽量です。
    • シングルスレッド: シングルスレッドですが、NodeJS は非同期の性質とイベント ループを使用して同時操作を処理します。
    • V8 上に構築: NodeJS は Google Chrome の V8 JavaScript エンジン上に構築されているため、JavaScript コードの実行が非常に高速になります。

NodeJS はバックグラウンドでどのように動作しますか?

  • イベントループ:

    • NodeJS はシングルスレッドのイベント ループで動作するため、スレッドをブロックすることなく複数の同時リクエストを処理できます。
    • イベント ループのフェーズ:
    • Timers: setTimeout() および setInterval() によってスケジュールされたコールバックを実行します。
    • 保留中のコールバック: I/O コールバックを次のループ反復に延期して実行します。
    • アイドル、準備: NodeJS によって内部的に使用されます。
    • ポーリング: 新しい I/O イベントを取得し、I/O 関連のコールバックを実行します。
    • Check: setImmediate() によってスケジュールされたコールバックを実行します。
    • Close Callbacks: close イベント コールバックを実行します。
  • ノンブロッキング 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。