npm install
せずにHTML表示できるnodeのサーバーを作ってみました。
server.js
const http = require('http'); const fs = require('fs'); const path = require('path'); const port = 3000; const getType = (url) => { const extname = path.extname(url); const types = { ".html": "text/html", ".css": "text/css", ".js": "text/javascript", ".png": "image/png", ".gif": "image/gif", ".svg": "svg+xml" }; return ( extname in types )? types[extname] : "text/plain"; }; const getErrorStatusCode = (err) => { let status = 500; switch(err.code) { case 'ENOENT': default: status = 404; break; } return status; }; const server = http.createServer((req, res) => { const url = path.relative('/', req.url); fs.readFile(url, (err, data) => { if(!err) { res.writeHead(200, {'Content-Type': getType(url)}); res.end(data); } else { // throw err するとコケる console.log(err, err.code); const statusCode = getErrorStatusCode(err); res.statusCode = statusCode res.writeHead(statusCode, {'Content-Type': 'text/plain'}); res.end(err.message); } }); }).listen(port); console.log(`Server running at http://localhost:${port}/`);
起動
$ node server.js
localhost:3000
にアクセス
ルーティングとか特に何もしてないので、server.js
があるディレクトリがルートなシンプルなサーバです。
作ってみて自分で言うのも何ですが、単に静的ファイル表示できるだけなら、http-server使った方が楽そうです。
それこそちょっと複雑なコトしたければExpressやVue
おまけ
先日参加したReproさんのハンズオンで、json-serverってシンプルなJSON返すサーバーがあることを教えてもらいました。nodeで動かせるので、nodeでサーバーも動かしてAPI使ったアプリのモックアップづくりにもとても良さそうだなーって思いました。
- http-server - npm
- node.jsでシンプルなwebサーバー - Qiita
- [Node.js] Webサーバ+アプリ構築が速すぎる件 〜 JSおくのほそ道 #004 - Qiita
- GitHub - typicode/json-server: Get a full fake REST API with zero coding in less than 30 seconds (seriously)
HARIO (ハリオ) V60 コーヒーサーバー 700ml VCS-02B
- 出版社/メーカー: HARIO(ハリオ)
- メディア: ホーム&キッチン
- クリック: 1回
- この商品を含むブログ (1件) を見る
ゼロからはじめるLinuxサーバー構築・運用ガイド 動かしながら学ぶWebサーバーの作り方
- 作者: 中島能和
- 出版社/メーカー: 翔泳社
- 発売日: 2016/07/06
- メディア: 大型本
- この商品を含むブログを見る