express.static()
で ./www
配下をホスティングするだけのスニペットです。
package.json
{
"name": "static file hosting",
"version": "0.1.0",
"description": "static file hosting",
"main": "app.mjs",
"type":"module",
"scripts": {
"start": "node ./app.mjs"
},
"author": "your name",
"license": "your license",
"dependencies": {
"express": "^4.21.1"
}
}
app.mjs .js
import http from 'http';
import express from 'express';
const LISTEN_IP = "127.0.0.1";
const LISTEN_PORT = 3000;
let webServer;
let app;
await runExpressApp();
await runWebServer();
async function runExpressApp() {
app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json({ extended: true }));
app.use('/',express.static("./www"));
}
async function runWebServer() {
webServer = http.createServer(app);
webServer.on('error', (err) => {
console.error('starting web server failed:', err.message);
});
await new Promise((resolve) => {
webServer.listen(LISTEN_PORT, () => {
console.log('server is running PORT:'+LISTEN_PORT);
resolve();
});
});
}
利用方法
npm i
npm start
ファイルを ./www/index.html
とかに入れればhttp://localhost:3000
で表示されます。