Nodejs with KOA2 by Amin B Nagpure - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

How to host project on Windows Sever 2008 R2

 

Requirement:

  • Dedicated server Windows 2008 R2
  • ISS 7.5
  • Node
  • IISNode
  • URL rewrite module for IIS

You should have good knowledge of iis manager, configuration of websites and security permissions.

Node:

  • Download and install latest stable version from
  • https://nodejs.org/en/
  • This will install node to c:/program files/nodejs

IISNode

URL rewrite module for IIS

Configure application for hosting

Now we have to do some changes to our application, like adding web.confige file, setting app.listen port and some changes in auth code.

Ok now hosting my site on http://websolnetwork.com/ with the help of Remote Desktop connection I am accessing my server.

Before uploading site add web.config file in app root folder.

./web.config

 

<configuration>

 <appSettings>

  <add key="BABEL_DISABLE_CACHE" value="true" />

 </appSettings>

 <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="babel.app.js" verb="*"

modules="iisnode" />

  </handlers>

  <rewrite>

   <rules>

    <rule name="NodeInspector" patternSyntax="ECMAScript"

stopProcessing="true">

     <match url="^babel.app.js\/debug[\/]?" />

    </rule>

    <rule name="LoginReg">

     <match url="/*" />

     <action type="Rewrite" url="babel.app.js" />

    </rule>

   </rules>

  </rewrite>

  <!--

      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;iisnode.yml"

    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="iisnode.yml"

     />

-->

  <!--    

     

    One more setting that can be modified is the path to the node.exe

executable and the interceptor:

    <iisnode

nodeProcessCommandLine="&quot;%programfiles%\nodejs\node.exe&quot;" /> -->

   <iisnode

      nodeProcessCommandLine="&quot;%programfiles%\nodejs\node.exe&quot;" 

      interceptor="&quot;%programfiles%\iisnode\interceptor.js&quot;"

   loggingEnabled="true"

    logDirectory="iisnode"

   debuggerExtensionDll="iisnode-inspector.dll"

    debuggingEnabled="true"

    debugHeaderEnabled="false"

    debuggerPortRange="5058-6058"

    debuggerPathSegment="debug"

    maxLogFileSizeInKB="128"

    maxTotalLogFileSizeInKB="1024"

    maxLogFiles="20"

   />

    

   

 

 </system.webServer>

</configuration>

Ok now some explanation of we are doing in web.confige file

<handlers>

 <add name="iisnode" path="babel.app.js" verb="*" modules="iisnode" />

</handlers>

This where we show the path=”babel.app.js” this our main application file to start application, remember we are running our app with babel.

<rewrite>

 <rules>

  <rule name="NodeInspector" patternSyntax="ECMAScript"

stopProcessing="true">

  <match url="^babel.app.js\/debug[\/]?" />

  </rule>

  <rule name="LoginReg">

   <match url="/*" />

   <action type="Rewrite" url="babel.app.js" />

  </rule>

 </rules>

</rewrite>

This is our url rewrite code for that you have to install URL rewrite module for IIS on your server first, by this code when you type http://websitname.com then it will automatically call babel.app.js file. If this code is note in your config file then you have to type http://websitname.com/babel.app.js and then it will run your app.

<iisnode nodeProcessCommandLine="&quot;%programfiles%\nodejs\node.exe&quot;"

/> -->

   <iisnode

      nodeProcessCommandLine="&quot;%programfiles%\nodejs\node.exe&quot;"

      interceptor="&quot;%programfiles%\iisnode\interceptor.js&quot;"

 loggingEnabled="true"

 logDirectory="iisnode"

 debuggerExtensionDll="iisnode-inspector.dll"

 debuggingEnabled="true"

 debugHeaderEnabled="false"

 debuggerPortRange="5058-6058"

 debuggerPathSegment="debug"

 maxLogFileSizeInKB="128"

 maxTotalLogFileSizeInKB="1024"

 maxLogFiles="20"

   />

Ok with this line of code we are showing our node.exe file path and issnode file path to our application. Logging enabled true this will create a iisnode directory in application folder and save log files in it. You can access it by websitname.com/iisnode/index.html.

Ok now before uploading we have to remove node_modules folder from application folder, or else it will take forever to upload. Don’t delete it directly delete it from command-prompt

Open command-prompt goto application directory and type following command

>rmdir node_modules/s

/? Will show you options for delete

After this some changes in app.js file

./app.js

//this will listen your app on http://localhost:3000

app.listen(3000);

console.log(‘App listening on port 3000’);

Remember previously we have wrote this code in our app.js file now change it to this

var port = process.env.PORT || 3000;

 

app.listen(port);

 

console.log("App is listening on port " + port);

 

process.env.PORT this will get the running port which port 80 or else we are running it locally then it will take port 3000.

Ok remember console Google API console we have created for localhost:3000 now create it for your website. Change it in ./auth.js file. Also change callback url to http://websitname.com/auth/google/callback.

Ok now upload your app on your server using ftp.

  • Now on server create a separate folder in c:/ with name test copy paste your app in it.
  • Go to command prompt with administrator permission go to your c:/test/application directory and type
  • >npm install
  • This will install all the dependencies in your application directory under node_modules folder.
  • Now go to your IIS Manager.
  • At left pane there is list of sites under site folder, if you have already created web site then you will find your site there, else create it, right click on site folder add website.
  • My site is already created using website panel.
  • Now click on site name go to basic settings, change application pool to DefaultAppPool, change physical path to you application c:/test/applicationDirectory click test settings this will show warning cannot verify access to path c:/test/applicationdirectory but neglect it it’s just a warning
  • Ok now close click ok
  • Right click on site name click edit permission go to security, see under groups or user names: there is a list of users see if there is a DefaultAppPool, if not then click edit then add, under enter object name to select, type
  • IIS AppPool\DefaultAppPool
  • Click on check names, if you haven’t done any speling mistake then it will show the DefaultAppPool in that box and then click ok
  • Now click apply, it will take some time to assign permission to your node_modules folder.
  • After it click ok may be two times.
  • Now you have to assign some permission to iisnode, node.exe in c:/programfile to access by IIS_USRS.
  • Same procedure right click security, check for IIS_USRS else, edit, add user type IIS_USRS check names and click ok
  • Remember no spelling mistakes.
  • Ok done now got to browser and type your sitename

Errors I got when hosting and how I fixed it

  • Permission errors 404 not found error, check for permissions you have assign to node.exe and iisnode-inspector.dll
  • Check all packages are installed properly else remove node_modules and again install all packages using administrator command prompt, after doing this again assign permissions to your site from iis manager
  • Check permissions for DefaultAppPool read/write execute are assigned
  • You may found error IISNode configuration error
  • Go to appsite iismanager right click recycle apppool
  • This will solve your error