首頁 > web前端 > js教程 > Node.js學習之靜態資源伺服器

Node.js學習之靜態資源伺服器

青灯夜游
發布: 2020-12-14 18:20:07
轉載
2965 人瀏覽過

Node.js學習之靜態資源伺服器

相關推薦:《nodejs 教學

#在建立HTTP 伺服器實作了一個最簡單的靜態資源伺服器,可以對程式碼進行寫改造,增加資料夾預覽功能,暴露出一些配置,變成一個可自訂的靜態資源伺服器模組

模組化

可自訂的靜態資源伺服器理想的使用方式應該是這樣的

1

2

3

4

5

6

7

8

9

10

const StaticServer = require('YOUR_STATIC_SERVER_FILE_PATH');

 

const staticServer = new StaticServer({

    port: 9527,

  root: '/public',

});

 

staticServer.start();

 

staticServer.close();

登入後複製

這樣的使用方式就要求程式碼實作模組化,Node.js 實作一個模組非常簡單

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

const http = require('http');

const fs = require('fs');

const path = require('path');

const mime = require('mime-types');

 

const defaultConf = require('./config');

 

class StaticServer {

  constructor(options = {}) {

    this.config = Object.assign(defaultConf, options);

  }

 

  start() {

    const { port, root } = this.config;

 

    this.server = http.createServer((req, res) => {

      const { url, method } = req;

 

      if (method !== 'GET') {

        res.writeHead(404, {

          'content-type''text/html',

        });

        res.end('请使用 GET 方法访问文件!');

        return false;

      }

 

      const filePath = path.join(root, url);

      fs.access(filePath, fs.constants.R_OK, err => {

        if (err) {

          res.writeHead(404, {

            'content-type''text/html',

          });

          res.end('文件不存在!');

 

        else {

          res.writeHead(200, {

            'content-type': mime.contentType(path.extname(url)),

          });

          fs.createReadStream(filePath).pipe(res);

        }

      });

    }).listen(port, () => {

      console.log(`Static server started at port ${port}`);

    });

  }

 

  stop() {

    this.server.close(() => {

      console.log(`Static server closed.`);

    });

  }

}

 

module.exports = StaticServer;

登入後複製

完整程式碼:https://github.com/Samaritan89/ static-server/tree/v1
執行npm run test 可以測試
Node.js學習之靜態資源伺服器
Node.js學習之靜態資源伺服器

##支援資料夾預覽

當存取的路徑是資料夾的時候程式會報錯

1

2

3

4

5

6

7

8

Error: EISDIR: illegal operation on a directory, read

Emitted 'error' event on ReadStream instance at:

    at internal/fs/streams.js:217:14

    at FSReqCallback.wrapper [as oncomplete] (fs.js:524:5) {

  errno: -21,

  code: 'EISDIR',

  syscall: 'read'

}

登入後複製
因為fs.createReadStream 嘗試讀取資料夾,需要相容下存取路徑是資料夾的時候,回傳一個目錄頁,也就是在fs.access 之後判斷檔案類型

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

fs.access(filePath, fs.constants.R_OK, err => {

  if (err) {

    res.writeHead(404, {

      'content-type''text/html',

    });

    res.end('文件不存在!');

 

  else {

    const stats = fs.statSync(filePath);

    const list = [];

    if (stats.isDirectory()) {

      // 如果是文件夹则遍历文件夹,生成改文件夹内的文件树

      // 遍历文件内容,生成 html

 

    else {

      res.writeHead(200, {

        'content-type': mime.contentType(path.extname(url)),

      });

      fs.createReadStream(filePath).pipe(res);

    }

  }

});

登入後複製
遍歷產生html 部分需要用到資料夾操作章節介紹的​​知識,為了方便產生HTML,demo 使用了Handlebar 範本引擎,主要邏輯

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

if (stats.isDirectory()) {

  // 如果是文件夹则遍历文件夹,生成改文件夹内的文件树

  const dir = fs.opendirSync(filePath);

  let dirent = dir.readSync();

  while (dirent) {

    list.push({

      name: dirent.name,

      path: path.join(url, dirent.name),

      type: dirent.isDirectory() ? 'folder' 'file',

    });

    dirent = dir.readSync();

  }

  dir.close();

 

  res.writeHead(200, {

    'content-type''text/html',

  });

 

  // 对文件顺序重排,文件夹在文件前面,相同类型按字母排序,不区分大小写

  list.sort((x, y) => {

    if (x.type > y.type) {

      // 'folder' > 'file', 返回 -1,folder 在 file 之前

      return -1;

    else if (x.type == y.type) {

      return compare(x.name.toLowerCase(), y.name.toLowerCase());

    else {

      return 1;

    }

  });

 

  // 使用 handlebars 模板引擎,生成目录页面 html

  const html = template({ list });

  res.end(html);

}

登入後複製
透過git 程式碼修改記錄可以清楚看到本次的變更:https://github.com/Samaritan89/static-server/commit/5565788dc317f29372f6e67e6fd55ec92323d0ea

##npm run test

 ,使用瀏覽器存取127.0.0.1:9527 可以看到目錄檔案的展示##完整程式碼:https://github. com/Samaritan89/static-server/tree/v2
Node.js學習之靜態資源伺服器更多程式相關知識,請造訪:
程式設計教學

! !

以上是Node.js學習之靜態資源伺服器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
node.js是用來做什麼的
來自於 1970-01-01 08:00:00
0
0
0
新手學習vue和node.js的困惑
來自於 1970-01-01 08:00:00
0
0
0
javascript - node.js i/o優化
來自於 1970-01-01 08:00:00
0
0
0
關於node.js,各位來指點下,謝謝哈( ⊙ o ⊙ )
來自於 1970-01-01 08:00:00
0
0
0
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板