ホームページ  >  記事  >  ウェブフロントエンド  >  Node を使用した単純な HTTP サーバーの作成の簡単な分析

Node を使用した単純な HTTP サーバーの作成の簡単な分析

青灯夜游
青灯夜游転載
2022-12-05 18:35:222131ブラウズ

NodeJS を使用して HTTP サーバーを作成するにはどうすればよいですか?次の記事では、Node を使用して簡単な HTTP サーバーを作成する方法を紹介します。

Node を使用した単純な HTTP サーバーの作成の簡単な分析

1. Node.js を使用して JavaScript スクリプトを直接実行する

node.js Chrome に基づく v8 エンジンは js コードを実行するため、ブラウザ環境を削除して js# を実行できます。コンソールで直接 ##次のようなコード ##hello worldcode<pre class="brush:php;toolbar:false">console.log('hello world');</pre>コンソールで

node

を使用して直接実行できます

Node を使用した単純な HTTP サーバーの作成の簡単な分析

#2. 単純な HTTP サーバーの作成

##node.js の組み込みモジュール## http

は、

CommonJS 仕様に基づいた基本的な http サービス機能を提供します。require を使用して、次の http モジュールをインポートできます。 http を使用します。 createServer 関数を使用すると、http サーバーを作成できます。 このコールバック関数は、パラメータとしてコールバック関数を受け取ります。このコールバック関数は、requestresponse という 2 つのパラメータを受け取ります。 [関連チュートリアルの推奨事項: nodejs ビデオ チュートリアル ] request には、

url
    、リクエスト ヘッダーなど、クライアントが要求したすべての情報が含まれます
  • header、リクエスト メソッド、リクエスト本文など。response は主にクライアントに情報を返すために使用され、# などの応答本文に関連するいくつかの操作をカプセル化します。 ## response.writeHead メソッドを使用すると、戻り本文のヘッダー情報とステータス コードをカスタマイズできます。
  • 応答本文を処理した後、response.end() を呼び出します。 メソッドは応答本文をクライアントに送信できます createServer
  • 関数を使用すると、
Server

オブジェクトが作成されるだけで、リッスンできるようにはなりません。また、server の listen## を呼び出す必要もあります。 オブジェクト。#このメソッドはリッスンに使用でき、実際にサーバーとして実行を開始できます。#listenメソッドの最初のパラメータはリッスンです。ポート番号、2 番目のパラメータはバインディング ホスト ip、3 番目のパラメータはコールバック関数で、

http
    モジュールによって非同期的に呼び出されます。エラーが発生した場合は、は、このコールバック関数の最初のパラメータで呼び出すことができます。スローされた例外を取得した後、サーバーをより堅牢にするために例外を処理することを選択できます。
  • 次は、## の使用例です。 #http 単純なサーバーを作成するモジュール
    const { createServer } = require('http');
    const HOST = 'localhost';
    const PORT = '8080';
    
    const server = createServer((req, resp) => {
      // the first param is status code it returns  
      // and the second param is response header info
      resp.writeHead(200, { 'Content-Type': 'text/plain' });  
      
      console.log('server is working...');  
      
      // call end method to tell server that the request has been fulfilled
      resp.end('hello nodejs http server');
    });
    
    server.listen(PORT, HOST, (error) => {  
    if (error) {  
      console.log('Something wrong: ', error);   
       return;
      }  
      console.log(`server is listening on http://${HOST}:${PORT} ...`);
    });
    node
  • を使用して直接実行して、自分に属するサーバーを作成してみることができます。サーバーが実行されたら、ブラウザは
http://localhost:8080

にアクセスしてサーバーにアクセスできます。nodemon を使用することもできます。 コードを変更したときにプログラムを手動で終了して再実行する必要がないように実行します。

npm i -g nodemon
グローバルにインストールして、アクセスせずに直接使用できるようにすることをお勧めします。

npx nodemon# 経由 ##使用するには 使い方も非常に簡単で、Node を使用した単純な HTTP サーバーの作成の簡単な分析node

コマンドを

nodemon コマンド

nodemon http-server.js

# コマンドに変更するだけです。 #3 .タイププロンプトを追加以前に

createServer

および Node を使用した単純な HTTP サーバーの作成の簡単な分析resp

オブジェクトを使用したときは、構文プロンプトが表示されなかったため、 # に従う必要があります。 # at any time. #node
使用中に公式ドキュメントを確認するのは少し不便です。 しかし、問題はありません。

ts.d.ts

ファイルを使用して、構文プロンプトを提供できます。

ts を使用していないことに注意してください。開発の場合は、それを使用するだけです。 構文プロンプト関数は、 プロジェクトを初期化するだけです -- npm init -yInstall@types/node -- pnpm i @types/node -D

    プロジェクト ディレクトリに
  1. jsconfig.json ファイルを作成し、node_modules
  2. を除外します。チェックする必要はありません
  3. <pre class="brush:php;toolbar:false">{  &quot;compilerOptions&quot;: {     &quot;checkJs&quot;: true   },     &quot;exclude&quot;: [&quot;node_modules&quot;, &quot;**/node_modules/*&quot;] }</pre> 上記のコードに実際にエラーがあることがわかったでしょうか? checkJs は型エラーのチェックに役立ちます。必要に応じて有効にするかどうかを選択できます。 ご覧のとおり、チェックをオンにすると、すぐにパラメーターの型の不一致の問題が表示されました。
  4. 这时候将鼠标悬浮在listen方法上,就能够看到该方法的签名

    Node を使用した単純な HTTP サーバーの作成の簡単な分析

    可以看到,原来port参数需要是number类型,但是我们定义的时候是string类型,所以没匹配上,将其修改为number8080即可 而且可以直接查看到相关api的文档,不需要打开node官方的文档找半天去查看了


    4. 返回多个字符串的响应体

    前面我们的简单http server中只返回了一句话,那么是否能够返回多句话呢? 这就要用到resp对象的write方法了,end只能够返回一次内容,而是用write方法,我们可以多次写入内容到响应体中,最后只用调用一次end,并且不传递任何参数,只让他完成发送响应体的功能

    const { createServer } = require("http");
    const HOST = "localhost";
    const PORT = 8080;
    
    const server = createServer((req, resp) => {
      resp.writeHead(200, { "Content-Type": "text/plain" });  
      console.log("server is working...");  
      
      // write some lorem sentences
      resp.write("Lorem ipsum dolor sit amet consectetur adipisicing elit.\n");
      resp.write("Omnis eligendi aperiam delectus?\n");
      resp.write("Aut, quam quo!\n");
    
      resp.end();
    });
    
    server.listen(PORT, HOST, (error) => {
      if (error) {    
      console.log("Something wrong: ", error);    
      return;
      }  
      console.log(`server is listening on http://${HOST}:${PORT} ...`);
    });

    这次我们写入了三句话,现在的效果就变成这样啦

    Node を使用した単純な HTTP サーバーの作成の簡単な分析


    5. 返回html

    我们不仅可以返回字符串给浏览器,还可以直接读取html文件的内容并将其作为结果返回给浏览器 这就需要用到另一个Node.js的内置模块 -- fs,该模块提供了文件操作的功能 使用fs.readFile可以异步进行读取文件的操作,但是它不会返回promise对象,因此我们需要传入回调去处理读取到文件后的操作 还可以使用fs.readFileSync进行同步阻塞读取文件,这里我们选择异步读取

    const { createServer } = require("http");
    const fs = require("fs");
    const HOST = "localhost";
    
    const PORT = 8080;const server = createServer((req, resp) => {
      // change the MIME type from text/plain to text/html
      resp.writeHead(200, { "Content-Type": "text/html" });  
      
      // read the html file content
      fs.readFile("index.html", (err, data) => { 
         if (err) {  
          console.error(      
            "an error occurred while reading the html file content: ",
            err
          );      throw err;
        }    
        console.log("operation success!");
    
        resp.write(data);
        resp.end();
      });
    });
    
    server.listen(PORT, HOST, (error) => {
      if (error) {    
      console.log("Something wrong: ", error);    
      return;
      }  
      console.log(`server is listening on http://${HOST}:${PORT} ...`);
    });

    现在的结果就像下面这样:

    Node を使用した単純な HTTP サーバーの作成の簡単な分析

    成功将html返回注意:这里需要将响应头的**Content-Type**改为**text/html**,告知浏览器我们返回的是**html**文件的内容,如果仍然以**text/plain**返回的话,浏览器不会对返回的内容进行解析,即便它是符合**html**语法的也不会解析,就像下面这样:

    Node を使用した単純な HTTP サーバーの作成の簡単な分析


    6. 返回JSON

    当我们需要编写一个后端服务器,只负责返回接口数据的时候,就需要返回json格式的内容了,相信聪明的你也知道该怎么处理了:

    1. MIME类型设置为application/json
    2. resp.write的时候传入的是json字符串,可以使用JSON.stringify处理对象后返回
    const { createServer } = require("http");
    const HOST = "localhost";
    const PORT = 8080;
    
    const server = createServer((req, resp) => { 
     // change the MIME type to application/json
      resp.writeHead(200, { "Content-Type": "application/json" });  
      
      // create a json data by using an object  
      const jsonDataObj = {
          code: 0,    
          message: "success",    
          data: {  
              name: "plasticine",      
              age: 20,      
              hobby: "coding",
        },
      };
    
      resp.write(JSON.stringify(jsonDataObj));
      resp.end();
    });
    
    server.listen(PORT, HOST, (error) => {
      if (error) { 
         console.log("Something wrong: ", error);    
         return;
      }  
      console.log(`server is listening on http://${HOST}:${PORT} ...`);
    });

    结果如下:

    Node を使用した単純な HTTP サーバーの作成の簡単な分析


    7. 返回pdf文件

    和之前返回html文件的思路类似,都是一个设置响应头MIME类型,读取文件,返回文件内容的过程 但是这次我们搞点不一样的 我们的思路是在服务器运行的时候生成一个pdf文件,并将它返回 还需要将MIME的类型改为application/pdf生成pdf文件需要用到一个库 -- pdfkit

    pnpm i pdfkit

    首先我们编写一个创建pdf文件的函数,因为创建pdf文件还需要进行一些写入操作,不确定什么时候会完成,但是我们的请求必须等到pdf文件创建完成后才能得到响应 所以我们需要将它变成异步进行的,返回一个promise

    /**
     * @description 创建 pdf 文件
     */const createPdf = () => {
       return new Promise((resolve, reject) => {
           if (!fs.existsSync("example.pdf")) {      
           // create a PDFDocument object      
           const doc = new PDFDocument();
           
           // create write stream by piping the pdf content.
           doc.pipe(fs.createWriteStream("example.pdf"));   
            
          // add some contents to pdf document
          doc.fontSize(16).text("Hello PDF", 100, 100);   
             
          // complete the operation of generating PDF file.
          doc.end();
        }
    
        resolve("success");
      });
    };

    这里使用到了管道操作,将PDFDocument对象的内容通过管道传到新创建的写入流中,当完成操作后我们就通过resovle告知外界已经创建好pdf文件了 然后在服务端代码中调用

    const server = createServer(async (req, resp) => {
      // change the MIME type to application/pdf
      resp.writeHead(200, { "Content-Type": "application/pdf" });  
      
      // create pdf file  
      await createPdf();  
      
      // read created pdf file
      fs.readFile("example.pdf", (err, data) => {
          if (err) { 
           console.error(        
            "an error occurred while reading the pdf file content: ",
            err
          );      
          throw err;
        }    
        console.log("operation success!");
    
        resp.end(data);
      });
    });
    
    server.listen(PORT, HOST, (error) => {
      if (error) {
          console.log("Something wrong: ", error);    
          return;
      }  
      console.log(`server is listening on http://${HOST}:${PORT} ...`);
    });

    现在浏览器就可以读取到创建的pdf文件了

    Node を使用した単純な HTTP サーバーの作成の簡単な分析


    8. 返回音频文件

    思路依然是一样的,读取一个音频文件,然后通过管道将它送到resp对象中再返回即可

    const { createServer } = require("http");
    const { stat, createReadStream } = require("fs");
    const HOST = "localhost";
    const PORT = 8080;
    
    const server = createServer((req, resp) => {
      // change the MIME type to audio/mpe
      resp.writeHead(200, { "Content-Type": "audio/mp3" });  
      const mp3FileName = "audio.mp3";
    
      stat(mp3FileName, (err, stats) => {
        if (stats.isFile()) {      
          const rs = createReadStream(mp3FileName);      
          
          // pipe the read stream to resp
          rs.pipe(resp);
        } else {
          resp.end("mp3 file not exists");
        }
      });
    });
    
    server.listen(PORT, HOST, (error) => {
      if (error) {    
      console.log("Something wrong: ", error);    
      return;
      }  
      console.log(`server is listening on http://${HOST}:${PORT} ...`);
    });

    效果如下

    1Node を使用した単純な HTTP サーバーの作成の簡単な分析

    打开后就是一个播放音频的界面,这是chrome提供的对音频文件的展示,并且打开控制台会发现有返回音频文件

    11-Node を使用した単純な HTTP サーバーの作成の簡単な分析

    注意:将音频文件流通过管道传到**resp**后,不需要调用**resp.end()**方法,因为这会关闭整个响应,导致音频文件无法获取

    1Node を使用した単純な HTTP サーバーの作成の簡単な分析

    1Node を使用した単純な HTTP サーバーの作成の簡単な分析


    9. 返回视频文件

    视频文件和音频文件的处理是一样的,只是MIME的类型要改成video/mp4,其他都一样

    const { createServer } = require("http");
    const { stat, createReadStream } = require("fs");
    const HOST = "localhost";
    const PORT = 8080;
    const server = createServer((req, resp) => {  
    // change the MIME type to audio/mpe
      resp.writeHead(200, { "Content-Type": "audio/mp4" });  
      const mp4FileName = "video.mp4";
    
      stat(mp4FileName, (err, stats) => { 
         if (stats.isFile()) {      
         const rs = createReadStream(mp4FileName);      
         // pipe the read stream to resp
          rs.pipe(resp);
        } else {
          resp.end("mp4 file not exists");
        }
      });
    });
    
    server.listen(PORT, HOST, (error) => { 
     if (error) {    
     console.log("Something wrong: ", error);    
     return;
      }  
      console.log(`server is listening on http://${HOST}:${PORT} ...`);
    });

    Node を使用した単純な HTTP サーバーの作成の簡単な分析


    总结

    我们学会了:

    • 如何使用Node创建一个http服务器
    • js加上类型提示
    • 如何返回字符串响应体
    • 如何返回html
    • 如何返回JSON
    • 如何生成并返回pdf文件
    • 如何返回音频文件
    • 如何返回视频文件

    虽然内容简单,但还是希望你能跟着动手敲一敲,不要以为简单就看看就算了,看了不代表会了,真正动手实现过后才会找到自己的问题

    更多node相关知识,请访问:nodejs 教程

以上がNode を使用した単純な HTTP サーバーの作成の簡単な分析の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はjuejin.cnで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。