hosting node.js applications in IIS since 2011自2011年以来在IIS中托管nodejs应用程序

samples demonstrating basic features of hosting node.js applications in IIS 7.x演示在IIS 7x中托管nodejs应用程序的基本功能的示例

helloworld

The title says it all. Key points are:标题说明了一切。关键点是:

visit the node.js endpoint at hello.js
debug node.js endpoint at hello.js/debug (requires WebKit enabled browser)
get a client side JavaScript file from helloClient.js

code

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
        res.end('Hello, world! [helloworld sample; iisnode version is ' 
          + process.env.IISNODE_VERSION + ', node version is ' + process.version + ']');
}).listen(process.env.PORT);  

web.config

<configuration>
  <system.webServer>

    <!-- indicates that the hello.js file is a node.js application 
    to be handled by the iisnode module -->

    <handlers>
      <add name="iisnode" path="hello.js" verb="*" modules="iisnode" />
    </handlers>
    
  </system.webServer>
</configuration>

logging

Node.js applications hosted in IIS capture stdout and stderr (console.log) and make the output available over HTTP.IIS中托管的Node.js应用程序捕获stdout和stderr(consolelog),并通过HTTP提供输出。

  1. output from console.log (or any stdout or stderr output) from a node.js application is captured, stored in a file on disk, and available through HTTPnodejs应用程序的console.log输出(或任何stdoutstderr输出)被捕获,存储在磁盘上的文件中,并可通过HTTP访问
  2. By default, given a node.js application at http://localhost/node/logging/hello.js, the logs are available at http://localhost/node/logging/iisnode/.默认情况下,给定一个位于http://localhost/node/logging/hello.js的Node.js应用程序,日志可在http://localhost/node/logging/iisnode/找到。
  3. Check the configuration sample to customize the logging behavior.检查配置示例以自定义日志记录行为。
visit the node.js endpoint at hello.js
visit the logs at logs (only available after you first visit the endpoint)
debug node.js endpoint at hello.js/debug (requires WebKit enabled browser)

code

var http = require('http');

http.createServer(function (req, res) {
    console.log('A new request arrived with HTTP headers: ' + JSON.stringify(req.headers));
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('Hello, world! [logging sample]');
}).listen(process.env.PORT);

console.log('Application has started at location ' + process.env.PORT);

web.config

<configuration>
  <system.webServer>

    <!-- indicates that the hello.js file is a node.js application 
    to be handled by the iisnode module -->

    <handlers>
      <add name="iisnode" path="hello.js" verb="*" modules="iisnode" />
    </handlers>
    
  </system.webServer>
</configuration>

defaultdocument

The <defaultDocument> element in web.config may specify a default node.js application file that IIS will serve when the request URL does not specify any file name, e.g. http://localhost/node/defaultdocument/.webconfig中的<defaultDocument>元素可以指定一个默认的nodejs应用程序文件,当请求URL没有指定任何文件名时,IIS将为其提供服务,例如。http://localhost/node/defaultdocument/

visit the default node.js endpoint
debug the endpoint at index.js/debug (requires WebKit enabled browser)

code [index.js]

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('You have reached the default node.js application at index.js! [defaultdocument sample]');
}).listen(process.env.PORT); 

web.config

<configuration>
  <system.webServer>
    
    <!-- indicates that the index.js file is a node.js application 
    to be handled by the iisnode module -->
    
    <handlers>
      <add name="iisnode" path="index.js" verb="*" modules="iisnode" />
    </handlers>
    
    <!-- adds index.js to the default document list to allow 
    URLs that only specify the application root location, 
    e.g. http://mysite.antarescloud.com/ -->
    
    <defaultDocument enabled="true">
      <files>
        <add value="index.js" />
      </files>
    </defaultDocument>
    
  </system.webServer>
</configuration>

configuration配置

There are several configuration options that can be controlled from the system.webServer/iisnode section of the web.config configuration file or the iisnode.yml file. Review web.config or iisnode.yml below for detailed description of them.有几个配置选项可以从web.config配置文件的system.webServer/iisnode部分或iisnode.yml文件进行控制。查看下面的web.configiisnode.yml,了解它们的详细描述。

visit the node.js endpoint at hello.js
visit the logs at logs (only available after you first visit the endpoint)
debug the hello.js endpoint at hello.js/debug (requires WebKit enabled browser)

code

var http = require('http');

http.createServer(function (req, res) {
    console.log('A new request arrived with HTTP headers: ' + JSON.stringify(req.headers));
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('Hello, world! [configuration sample]');
}).listen(process.env.PORT);

console.log('Application started at location ' + process.env.PORT);

web.config

<configuration>
  <system.webServer>

    <!-- indicates that the hello.js file is a node.js application 
    to be handled by the iisnode module -->

    <handlers>
      <add name="iisnode" path="hello.js" verb="*" modules="iisnode" />
    </handlers>

    <!-- 
      the iisnode section configures the behavior of the node.js IIS module 
      setting values below are defaults
    
    * node_env - determines the environment (production, development, staging, ...) in which 
      child node processes run; if nonempty, is propagated to the child node processes as their NODE_ENV
      environment variable; the default is the value of the IIS worker process'es NODE_ENV
      environment variable

    * nodeProcessCommandLine - command line starting the node executable; in shared
      hosting environments this setting would typically be locked at the machine scope.

    * interceptor - fully qualified file name of a node.js application that will run instead of an actual application
      the request targets; the fully qualified file name of the actual application file is provided as the first parameter
      to the interceptor application; default interceptor supports iisnode logging
      
    * nodeProcessCountPerApplication - number of node.exe processes that IIS will start per application;
      setting this value to 0 results in creating one node.exe process per each processor on the machine
      
    * maxConcurrentRequestsPerProcess - maximum number of reqeusts one node process can 
      handle at a time
      
    * maxNamedPipeConnectionRetry - number of times IIS will retry to establish a named pipe connection with a
      node process in order to send a new HTTP request
      
    * namedPipeConnectionRetryDelay - delay in milliseconds between connection retries

    * maxNamedPipeConnectionPoolSize - maximum number of named pipe connections that will be kept in a connection pool; 
      connection pooling helps improve the performance of applications that process a large number of short lived HTTP requests
      
    * maxNamedPipePooledConnectionAge - age of a pooled connection in milliseconds after which the connection is not reused for
      subsequent requests
    
    * asyncCompletionThreadCount - size of the IO thread pool maintained by the IIS module to process asynchronous IO; setting it
      to 0 (default) results in creating one thread per each processor on the machine
    
    * initialRequestBufferSize - initial size in bytes of a memory buffer allocated for a new HTTP request
    
    * maxRequestBufferSize - maximum size in bytes of a memory buffer allocated per request; this is a hard limit of 
      the serialized form of HTTP request or response headers block

    * watchedFiles - semi-colon separated list of files that will be watched for changes; a change to a file causes the application to recycle;
      each entry consists of an optional directory name plus required file name which are relative to the directory where the main application entry point 
      is located; wild cards are allowed in the file name portion only; for example: "*.js;node_modules\foo\lib\options.json;app_data\*.config.json"
      
    * uncFileChangesPollingInterval - applications are recycled when the underlying *.js file is modified; if the file resides
      on a UNC share, the only reliable way to detect such modifications is to periodically poll for them; this setting 
      controls the polling interval
      
    * gracefulShutdownTimeout - when a node.js file is modified, all node processes handling running this application are recycled;
      this setting controls the time (in milliseconds) given for currently active requests to gracefully finish before the 
      process is terminated; during this time, all new requests are already dispatched to a new node process based on the fresh version 
      of the application
    
    * loggingEnabled - controls whether stdout and stderr streams from node processes are captured and made available over HTTP
    
    * logDirectory - directory name relative to the main application file that will store files with stdout and stderr captures; 
      individual log file names have unique file names; log files are created lazily (i.e. when the process actually writes something
      to stdout or stderr); an HTML index of all log files is also maintained as index.html in that directory;
      by default, if your application is at http://foo.com/bar.js, logs will be accessible at http://foo.com/iisnode;
      SECURITY NOTE: if log files contain sensitive information, this setting should be modified to contain enough entropy to be considered
      cryptographically secure; in most situations, a GUID is sufficient
      
    * debuggingEnabled - controls whether the built-in debugger is available
      
    * debuggerPortRange - range of TCP ports that can be used for communication between the node-inspector debugger and the debugee; iisnode
      will round robin through this port range for subsequent debugging sessions and pick the next available (free) port to use from the range
      
    * debuggerPathSegment - URL path segment used to access the built-in node-inspector debugger; given a node.js application at 
      http://foo.com/bar/baz.js, the debugger can be accessed at http://foo.com/bar/baz.js/{debuggerPathSegment}, by default
      http://foo.com/bar/baz.js/debug
    
    * debugHeaderEnabled - boolean indicating whether iisnode should attach the iisnode-debug HTTP response header with 
      diagnostics information to all responses

    * maxLogFileSizeInKB - maximum size of a single log file in KB; once a log file exceeds this limit a new log file is created

    * maxTotalLogFileSizeInKB - maximum total size of all log files in the logDirectory; once exceeded, old log files are removed
    
    * maxLogFiles - maximum number of log files in the logDirectory; once exceeded, old log files are removed
    
    * devErrorsEnabled - controls how much information is sent back in the HTTP response to the browser when an error occurrs in iisnode; 
      when true, error conditions in iisnode result in HTTP 200 response with the body containing error details; when false,
      iisnode will return generic HTTP 5xx responses

    * flushResponse - controls whether each HTTP response body chunk is immediately flushed by iisnode; flushing each body chunk incurs 
      CPU cost but may improve latency in streaming scenarios

    * enableXFF - controls whether iisnode adds or modifies the X-Forwarded-For request HTTP header with the IP address of the remote host

    * promoteServerVars - comma delimited list of IIS server variables that will be propagated to the node.exe process in the form of 
      x-iisnode-<server_variable_name> HTTP request headers; for a list of IIS server variables available see 
      http://msdn.microsoft.com/en-us/library/ms524602(v=vs.90).aspx; for example "AUTH_USER,AUTH_TYPE"
      
    * configOverrides - optional file name containing overrides of configuration settings of the iisnode section of web.config; 
      the format of the file is a small subset of YAML: each setting is represented as a <key>: <value> on a separate line 
      and comments start with # until the end of the line, e.g. 
            # This is a sample iisnode.yml file
            nodeProcessCountPerApplication: 2
            maxRequestBufferSize: 8192 # increasing from the default
            # maxConcurrentRequestsPerProcess: 512 - commented out setting

    -->
    
    <iisnode      
      node_env="%node_env%"
      nodeProcessCountPerApplication="1"
      maxConcurrentRequestsPerProcess="1024"
      maxNamedPipeConnectionRetry="100"
      namedPipeConnectionRetryDelay="250"      
      maxNamedPipeConnectionPoolSize="512"
      maxNamedPipePooledConnectionAge="30000"
      asyncCompletionThreadCount="0"
      initialRequestBufferSize="4096"
      maxRequestBufferSize="65536"
      watchedFiles="*.js;node.conf"
      uncFileChangesPollingInterval="5000"
      gracefulShutdownTimeout="60000"
      loggingEnabled="true"
      logDirectory="iisnode"
      debuggingEnabled="true"
      debugHeaderEnabled="false"
      debuggerPortRange="5058-6058"
      debuggerPathSegment="debug"
      maxLogFileSizeInKB="128"
      maxTotalLogFileSizeInKB="1024"
      maxLogFiles="20"
      devErrorsEnabled="true"
      flushResponse="false"
      enableXFF="false"
      promoteServerVars=""
      configOverrides="node.conf"
     />

    <!--     
    
    One more setting that can be modified is the path to the node.exe executable:
    
    <iisnode
      nodeProcessCommandLine="&quot;%programfiles%\nodejs\node.exe&quot;" 
      interceptor="&quot;%programfiles%\iisnode\interceptor.js&quot;" />
    
    -->

    
  </system.webServer>
</configuration>

iisnode.yml

# The optional iisnode.yml file provides overrides of the iisnode configuration settings specified in web.config.

# node_env - determines the environment (production, development, staging, ...) in which
# child node processes run; if nonempty, is propagated to the child node processes as their NODE_ENV
# environment variable; the default is the value of the IIS worker process'es NODE_ENV
# environment variable

node_env:

# nodeProcessCommandLine - command line starting the node executable; in shared
# hosting environments this setting would typically be locked at the machine scope.

# nodeProcessCommandLine: "C:\Program Files\nodejs\node.exe"

# interceptor - fully qualified file name of a node.js application that will run instead of an actual application
# the request targets; the fully qualified file name of the actual application file is provided as the first parameter
# to the interceptor application; default interceptor supports iisnode logging

# interceptor: "c:\Program Files\iisnode\interceptor.js"

# nodeProcessCountPerApplication - number of node.exe processes that IIS will start per application;
# setting this value to 0 results in creating one node.exe process per each processor on the machine

nodeProcessCountPerApplication: 1

# maxConcurrentRequestsPerProcess - maximum number of reqeusts one node process can
# handle at a time

maxConcurrentRequestsPerProcess: 1024

# maxNamedPipeConnectionRetry - number of times IIS will retry to establish a named pipe connection with a
# node process in order to send a new HTTP request

maxNamedPipeConnectionRetry: 100

# namedPipeConnectionRetryDelay - delay in milliseconds between connection retries

namedPipeConnectionRetryDelay: 250

# maxNamedPipeConnectionPoolSize - maximum number of named pipe connections that will be kept in a connection pool;
# connection pooling helps improve the performance of applications that process a large number of short lived HTTP requests

maxNamedPipeConnectionPoolSize: 512

# maxNamedPipePooledConnectionAge - age of a pooled connection in milliseconds after which the connection is not reused for
# subsequent requests

maxNamedPipePooledConnectionAge: 30000

# asyncCompletionThreadCount - size of the IO thread pool maintained by the IIS module to process asynchronous IO; setting it
# to 0 (default) results in creating one thread per each processor on the machine

asyncCompletionThreadCount: 0

# initialRequestBufferSize - initial size in bytes of a memory buffer allocated for a new HTTP request

initialRequestBufferSize: 4096

# maxRequestBufferSize - maximum size in bytes of a memory buffer allocated per request; this is a hard limit of
# the serialized form of HTTP request or response headers block

maxRequestBufferSize: 65536

# watchedFiles - semi-colon separated list of files that will be watched for changes; a change to a file causes the application to recycle;
# each entry consists of an optional directory name plus required file name which are relative to the directory where the main application entry point
# is located; wild cards are allowed in the file name portion only; for example: "*.js;node_modules\foo\lib\options.json;app_data\*.config.json"

watchedFiles: *.js;iisnode.yml

# uncFileChangesPollingInterval - applications are recycled when the underlying *.js file is modified; if the file resides
# on a UNC share, the only reliable way to detect such modifications is to periodically poll for them; this setting
# controls the polling interval

uncFileChangesPollingInterval: 5000

# gracefulShutdownTimeout - when a node.js file is modified, all node processes handling running this application are recycled;
# this setting controls the time (in milliseconds) given for currently active requests to gracefully finish before the
# process is terminated; during this time, all new requests are already dispatched to a new node process based on the fresh version
# of the application

gracefulShutdownTimeout: 60000

# loggingEnabled - controls whether stdout and stderr streams from node processes are captured and made available over HTTP

loggingEnabled: true

# logDirectory - directory name relative to the main application file that will store files with stdout and stderr captures; 
# individual log file names have unique file names; log files are created lazily (i.e. when the process actually writes something
# to stdout or stderr); an HTML index of all log files is also maintained as index.html in that directory;
# by default, if your application is at http://foo.com/bar.js, logs will be accessible at http://foo.com/iisnode;
# SECURITY NOTE: if log files contain sensitive information, this setting should be modified to contain enough entropy to be considered
# cryptographically secure; in most situations, a GUID is sufficient

logDirectory: iisnode

# debuggingEnabled - controls whether the built-in debugger is available

debuggingEnabled: true

# debuggerPortRange - range of TCP ports that can be used for communication between the node-inspector debugger and the debugee; iisnode
# will round robin through this port range for subsequent debugging sessions and pick the next available (free) port to use from the range

debuggerPortRange: 5058-6058

# debuggerPathSegment - URL path segment used to access the built-in node-inspector debugger; given a node.js application at
http://foo.com/bar/baz.js, the debugger can be accessed at http://foo.com/bar/baz.js/{debuggerPathSegment}, by default
http://foo.com/bar/baz.js/debug

debuggerPathSegment: debug

# debugHeaderEnabled - boolean indicating whether iisnode should attach the iisnode-debug HTTP response header with 
# diagnostics information to all responses

debugHeaderEnabled: false

# maxLogFileSizeInKB - maximum size of a single log file in KB; once a log file exceeds this limit a new log file is created

maxLogFileSizeInKB: 128

# maxTotalLogFileSizeInKB - maximum total size of all log files in the logDirectory; once exceeded, old log files are removed

maxTotalLogFileSizeInKB: 1024
    
# maxLogFiles - maximum number of log files in the logDirectory; once exceeded, old log files are removed

maxLogFiles: 20

devErrorsEnabled: true

# flushResponse - controls whether each HTTP response body chunk is immediately flushed by iisnode; flushing each body chunk incurs
# CPU cost but may improve latency in streaming scenarios

flushResponse: false

# enableXFF - controls whether iisnode adds or modifies the X-Forwarded-For request HTTP header with the IP address of the remote host

enableXFF: false

# promoteServerVars - comma delimited list of IIS server variables that will be propagated to the node.exe process in the form of
# x-iisnode-<server_variable_name>
# HTTP request headers; for a list of IIS server variables available see
# http://msdn.microsoft.com/en-us/library/ms524602(v=vs.90).aspx; for example "AUTH_USER,AUTH_TYPE"

promoteServerVars:

urlrewrite

This sample demonstrates the use of IIS URL rewrite module to redirect an entire branch of the URL namespace to a single node.js application. This mechanism allows more control over the URL structure of a node.js web service as well as removes the *.js file name from the URL.此示例演示了如何使用IIS URL重写模块将URL命名空间的整个分支重定向到单个node.js应用程序。此机制允许对node.js web服务的URL结构进行更多控制,并从URL中删除*.js文件名。

visit the endpoint at myapp/foo/bar/baz
visit the endpoint at myapp/1/2/3?param=4
debug the hello.js application at hello.js/debug (requires WebKit enabled browser)

code

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('Hello from urlrewrite sample. Request path: ' + req.url);
}).listen(process.env.PORT);

web.config

<configuration>
  <system.webServer>

    <!-- indicates that the hello.js file is a node.js application 
    to be handled by the iisnode module -->

    <handlers>
      <add name="iisnode" path="hello.js" verb="*" modules="iisnode" />
    </handlers>

    <!-- use URL rewriting to redirect the entire branch of the URL namespace
    to hello.js node.js application; for example, the following URLs will 
    all be handled by hello.js:
    
        http://localhost/node/urlrewrite/myapp
        http://localhost/node/urlrewrite/myapp/foo
        http://localhost/node/urlrewrite/myapp/foo/bar/baz?param=bat
        
    -->
    
    <rewrite>
      <rules>
        <rule name="myapp">
          <match url="myapp/*" />
          <action type="Rewrite" url="hello.js" />
        </rule>
      </rules>
    </rewrite>

  </system.webServer>
</configuration>

express

node.js apps that use the popular express framework can be hosted in IIS.

visit the foo endpoint at myapp/foo
visit the bar endpoint at myapp/bar
visit the nonexistent endpoint at myapp/idontexist
debug the application at hello.js/debug (requires WebKit enabled browser)

code

var express = require('express');

var app = express.createServer();

app.get('/node/express/myapp/foo', function (req, res) {
    res.send('Hello from foo! [express sample]');
});

app.get('/node/express/myapp/bar', function (req, res) {
    res.send('Hello from bar! [express sample]');
});

app.listen(process.env.PORT);

web.config

<configuration>
  <system.webServer>

    <!-- indicates that the hello.js file is a node.js application 
    to be handled by the iisnode module -->

    <handlers>
      <add name="iisnode" path="hello.js" verb="*" modules="iisnode" />
    </handlers>

    <!-- use URL rewriting to redirect the entire branch of the URL namespace
    to hello.js node.js application; for example, the following URLs will 
    all be handled by hello.js:
    
        http://localhost/node/express/myapp/foo
        http://localhost/node/express/myapp/bar
        
    -->

    <rewrite>
      <rules>
        <rule name="myapp">
          <match url="myapp/*" />
          <action type="Rewrite" url="hello.js" />
        </rule>
      </rules>
    </rewrite> 
    
  </system.webServer>
</configuration>

project site: https://github.com/tjanczuk/iisnode