1. 程式人生 > 實用技巧 >Node.js 學習筆記之二:基本使用

Node.js 學習筆記之二:基本使用

示例1. 跟大家說 Hello

由於 Node.js 只是 JavaScript 程式的執行時環境,所以它並不會限制 JavaScript 程式碼的具體執行形式。為了說明這一點,本示例將使用四種形式來跟大家說"Hello"。首先,我們要在code目錄下執行mkdir 01_sayHello命令來建立用於存放這一組示例的目錄。

1. 終端輸出

在終端輸出資訊需要呼叫console.log()方法,下面來建立第一個 Node.js 指令碼,步驟如下:

  1. code/01_sayHello目錄下執行touch 01-sayHello.js命令。

  2. 執行vim 01-sayHello.js

    命令開啟該指令碼檔案。

  3. 01-sayHello.js指令碼檔案中輸入如下程式碼:

    const name = 'owlman'
    console.log('你好!', name)  // 輸出:你好!owlman
    
  4. 儲存檔案後,在code/01_sayHello目錄下執行node 01-sayHello.js命令,就可以看到輸出結果:

2. 檔案讀寫

用 Node.js 指令碼讀文字檔案需要呼叫fs.readFile()方法,具體步驟如下:

  1. code/01_sayHello目錄下執行touch 01-readFile.js命令。

  2. code/01_sayHello目錄下執行mkdir data

    命令,建立用於存放檔案的目錄。

  3. code/01_sayHello/data目錄下執行touch text-data.txt命令,並在其中輸入以下內容:

    Hello,owlman,歡迎學習 Nodejs。
    
    接下來,請讀取下面這首詩:
    
    朝辭白帝彩雲間,
    千里江陵一日還。
    兩岸猿聲啼不住,
    輕舟已過萬重山。
    
  4. code/01_sayHello目錄下執行vim 01-readFile.js命令開啟指令碼檔案,輸入如下程式碼:

    const fs = require('fs')
    fs.readFile('./data/text-data.txt', function(err, data) {
        if (err !== null ) {
           return console.error('錯誤資訊:' + err.message)
        }
        console.log(data.toString())
    })
    
  5. 儲存檔案後,在code/01_sayHello目錄下執行node 01-readFile.js命令,就可以看到相關內容已被輸出到終端中:

用 Node.js 指令碼寫文字檔案需要呼叫fs.writeFile()方法,具體步驟如下:

  1. code/01_sayHello目錄下執行touch 01-writeFile.js命令。

  2. code/01_sayHello目錄下執行vim 01-writeFile.js命令開啟指令碼檔案,並輸入如下程式碼:

    const fs = require('fs')
    const str = '你好,Nodejs!'
    
    fs.writeFile('./data/output.txt', str, function(err) {
        if (err !== null ) {
           return console.error('錯誤資訊:' + err.message)
        }
        console.log("檔案寫入成功!")
    })
    
  3. 儲存檔案後,在code/01_sayHello目錄下執行node 01-writeFile.js命令,就可以看到相關內容已經被寫入output.txt檔案:

3. Web 服務

用 Node.js 指令碼建立 Web 服務需要用到http模組,具體步驟如下:

  1. code/01_sayHello目錄下執行touch 01-webServer.js命令。

  2. 執行vim 01-webServer.js命令開啟指令碼檔案,輸入如下程式碼:

    const http = require('http')
    const server = http.createServer()
    
    server.on('request', function(req, res){
        res.end('<h1>你好,Nodejs!</h1>')
    })
    
    server.listen(8080, function(){
        console.log('請訪問http://localhost:8080/,按Ctrl+C終止服務!')
    })
    
  3. 儲存檔案後,在code/01_sayHello目錄下執行node 01-webServer.js命令,並用瀏覽器訪問http://localhost:8080/,就可以看到一個顯示<h1>標籤的頁面:

4. TCP 服務

用 Node.js 構建 TCP 服務需要用到net模組,具體步驟如下:

  1. code/01_sayHello目錄下執行touch 01-tcpServer.js命令。

  2. 執行vim 01-tcpServer.js命令開啟指令碼檔案,輸入如下程式碼:

    const net = require('net')
    const server = net.createServer(function (socket) {
        console.log('連線來自' + socket.remoteAddress)
        socket.end('你好,Nodejs!\n')
    })
    
    server.listen(7000, 'localhost', function(){
        console.log('TCP伺服器監聽 localhost 的 7000 埠,按 Ctrl+C 終止服務!')
    })
    
  3. 儲存檔案後,在code/01_sayHello目錄下執行node 01-tcpServer.js命令,並用telnet localhost 7000命令測試該伺服器,結果如下:

示例2. 自定義模組及其使用方式

本示例將致力於演示 Node.js 的自定義模組語法以及部分 ES6 新增的語法。首先,我們要在code目錄下執行mkdir 02_useModule命令來建立這一組示例的目錄。

1. 單檔案模組

  1. code/02_useModule目錄下執行touch 02-singleFile.js命令,建立指令碼檔案,並輸入如下程式碼:

    class singleFile_module {
        constructor() {
            this.name = 'singleFile_module'
        }
    
        sayhello() {
            console.log('Hello', this.name)
        }
    }
    
    module.exports = singleFile_module
    
  2. code/02_useModule目錄下執行touch 02-test.js命令,建立指令碼檔案,並輸入如下程式碼:

    const es5_syntax = require('./02-singleFile')
    const testobj = new singleFile_module()
    testobj.sayhello()
    
  3. 儲存檔案後,在code/02_useModule目錄下執行node 02-test.js命令,結果如下:

2. 多檔案模組

  1. code/02_useModule目錄下執行mkdir 02-multiFile命令,並進入到該目錄中執行npm init -y命令,建立模組目錄。

  2. code/02_useModule/02-multiFile目錄下執行touch functions.js命令,建立指令碼檔案,並輸入如下程式碼:

    function add(x,y){
        return x + y
    }
    
    exports.add = add
    
  3. code/02_useModule/02-multiFile目錄下執行touch dataObj.js命令,建立指令碼檔案,並輸入如下程式碼:

    const name = 'multFile_module'
    
    exports.name = name
    
  4. code/02_useModule/02-multiFile目錄下執行touch index.js命令,建立指令碼檔案,並輸入如下程式碼:

    const func = require('./functions')
    const str = require('./dataObj')
    
    class multiFile_module {
        constructor() {
            this.func = func.add
            this.name = str.name
        }
    
        sayhello() {
            console.log('Hello', this.name)
            console.log('x + y = ', this.func(10,5))
        }
    }
    
    module.exports = multiFile_module
    
  5. code/02_useModule目錄下將02-test.js指令碼修改如下:

    const singleFile_module = require(`./02-singleFile`)
    const testobj = new singleFile_module()
    testobj.sayhello()
    
    const multiFile_module = require(`./02-multiFile`)
    const testobj2 = new multiFile_module()
    testobj2.sayhello()
    
  6. 儲存所有檔案後,在code/02_useModule目錄下執行node 02-test.js命令,結果如下: