選單
GSS 技術部落格
在這個園地裡我們將從技術、專案管理、客戶對談面和大家分享我們多年的經驗,希望大家不管是喜歡或是有意見,都可以回饋給我們,讓我們有機會和大家對話並一起成長!
若有任何問題請來信:gss_crm@gss.com.tw
3 分鐘閱讀時間 (605 個字)

Hosting node.js express app in IIS

Hosting node.js express app in IIS


我們有一個「Local DirectLine」服務,是使用 Node.JS 寫的,寫好了之後要部署到Windows 2012 的 IIS 上,要如何進行呢? 以下將一步步介紹給大家。

1.安裝 Node.js

首先當然要在 Windows Server 上安裝所需要的 Node.JS 的版本,目前我們使用 v6.11.2 LTS 版本。

2.安裝 iisnode

請到 Azure/iisnode 下載 IIS 版本對應的 iisnode 並安裝起來。

iisnodesetup

3.安裝 IIS URL Rewrite Module

請到 IIS URL Rewrite 下載,在最下面會有各語系及x86/x64 可供安裝。安裝完成後,在 IIS 中就會多了 URL Rewrite ,如下圖,

urlrewrite

4.建立 IIS 應用程式,並新增 iisnode 處理常式對應

在建立的應用程式的「處理常式對應」中,新增模組對應(我的入口程式是 index.js ,您也可以用 *.js 或是您的 js 檔),如下,

iishandler

5.設定 URL 對應

我們需要將本應用程式目錄中的程式 Request 轉給我們程式 index.js 來執行,所以要設定 URL Rewrite,web.config 設定如下,

<rewrite> <rewrite> <rules> <rule name="all"> <match url="/*" /> <action type="Rewrite" url="index.js" /> </rule> </rules></rewrite>

6.web.config中設定應用程式目錄(假設我們建立的目錄是 LDL) ,web.config 設定如下,

<appSettings><appSettings> <add key="virtualDirPath" value="/LDL" /></appSettings>

註.1:測試的 index.js 內容如下,一般來說 app.get 都會直接用 / 開始,但是在 iis 中我們需要加入 virtualDirPath 哦!
var virtualDirPath = process.env.virtualDirPath || '';
var app = require('express')();
app.get(virtualDirPath + '/', (req, res) => {
res.send(virtualDirPath: ${virtualDirPath});
});
app.get(virtualDirPath + '/directline', (req, res) => {
res.send(virtualDirPath: ${virtualDirPath}/directline);
});
app.listen(process.env.PORT);

透過 Browser 開啟 http://localhost/ldl 就可以發現會正常的顯示出目錄的名稱就表示 OK 了。

註.2:如果您跟筆者使用 nvm 來管理 Node.JS 的版本,則要在 nvm 的目錄設定權限給IIS的執行者哦,如下圖,

nvmSecurity

註.3:在 iisnode 中執行的一些問題參考

3.1. process.env.PORT 的內容會類似是 .\pipe\88731ae5-10c4-42dd-8685-91ecf6f13861 ,所以它不是數值哦!
3.2. 有時 console.log 會造成它 GG 哦,如下圖 ! 如何更快速的找到錯誤的方式,筆者有找到時,再跟大家分享哦! iisnodeGG

所以 Local DirectLine 設定到 IIS 上運作是正常的哦! 如下圖,

ldlIIS

整個的 web.config,及最新的 index.js ,請參考 Local DirectLine 內容哦!

7.設定應用程式的目錄安全性(console.log)

需要在我們的應用程式目錄下,針對 iisnode 目錄設定安全性,讓在 Node.JS 中的 Console.Log 內容可以寫到該目錄之中。

因為我的 application pool 的帳號是使用 network service ,所以我們需要在 iisnode 目錄設定它允許「修改、讀取和執行 …」如下圖,

iisnodeSecurity

如果您沒有設定這個權限的話,當您程式中有寫 Console.Log 時,會出現類似以下的錯誤哦!

Error: EPERM: operation not permitted, open ‘C:\Program Files\Galaxy Software Services\LocalDirectline\iisnode\myservername-4220-stdout-1504572946040.txt'<br>    at Error (native)<br>    at Object.fs.openSync (fs.js:641:18)<br>    at Object.fs.writeFileSync (fs.js:1347:33)<br>    at SyncWriteStream.stream.write.stream.end (C:\Program Files\iisnode\interceptor.js:180:20)<br>    at Console.log (console.js:43:16)  ...

以上的說明希望對大家使用 node.js 在 iis 上運行有所幫助。

參考資料

Hosting Node.js projects in IIS virtual directories
Local DirectLine
在Window IIS中安装运行node.js应用—你疯了吗
在Window IIS上跑NodeJs
Linux 系統中 Docker 的設計與實作

相關文章

 

評論

尚無評論
已經注冊了? 這裡登入
Guest
2024/05/04, 週六

Captcha 圖像