First, create a run.cjs file and update this file to import your Node.js site entry point file (server.js) and configure it as the iisnode's entry point ( in web.config).
run.cjs:
import ("./server.js");
The cjs file extension is important because it tells Node that this file is not an ES module, as it would expect because of "type": "module" in the package.json. It allows other CommonJS files to include our new file - namely iisnode's interceptor.js. It again imports the server.js which then runs fine as ES module.
Below is a demo entry point file server.js.
server.js:
import express from 'express';
const app = express ();
app.get ('/',(req, res) => { const body = "hello this is a ES6 import demo project" // Adds header res.append ('Content-Type', 'text/plain;charset=utf-8'); res.append ('Connection', 'keep-alive') res.append ('Set-Cookie', 'divehours=fornightly') res.append ('Content-Length', Buffer.byteLength (body, 'utf-8')); res.status (200).send (body); })
const PORT = process.env.PORT;
app.listen (PORT,() => { console.log (Running on PORT ${PORT}); })
The below code will set your site default routing for iisnode.
web.config:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="iisnode" path="run.cjs" verb="*" modules="iisnode" />
</handlers>
<rewrite>
<rules> <!-- All other URLs are mapped to the node.js site entry point >
<rule name="DynamicContent">
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
</conditions>
<action type="Rewrite" url="run.cjs"/>
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Import using ES modules: Since Node v8.5, developers have been able to run variations of support for the ES modules specification using the --experimental-modules flag. These modules can be defined in either.mjs files or.js files also by adding { "type": "module" } in the package.json.
package.json:
{ "name": "index", "version": "1.0.0", "description": "", "main": "server.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node --experimental-modules server.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "^4.18.1" } }
Now your site will auto redirect to run.cjs file and auto enter your site entry point file (server.js).