2021年5月29日土曜日

denoでブラウザを起動してindex.htmlとcss.cssをロードするだけのwebServer

ファイルの種類に応じてcontent-typeの中身を変えないとcssファイルが有効にならなかった。
.greenText{color:#0f0}
view raw css.css hosted with ❤ by GitHub
// --allow-run --allow-net --allow-read
import { serve } from "https://deno.land/std@0.86.0/http/server.ts";
import * as path from "https://deno.land/std@0.97.0/path/mod.ts";
function pathResolver(meta: ImportMeta): (p: string) => string {
return (p) => path.fromFileUrl(new URL(p, meta.url))
}
const resolve = pathResolver(import.meta);
async function サーバ起動後(サーバ: any){
for await (const request of サーバ) {
if(request.method != 'GET'){return}
アドレス毎(request)
}
}
async function アドレス毎(request: any){
console.log('url:[' + request.url + ']')
let url = request.url
if(url=='/'){ url = './index.html' }
if(url.indexOf('/')==0){ url = '.' + url }
url = resolve(url)
const ファイルの有無 = await fileExists(url)
if(!ファイルの有無){
return request.respond({ status: 404 })
}
const file = await Deno.open(url);
request.respond({
status: 200,
headers: new Headers({"content-type": 拡張子2contentType(url)}),
body: file
});
}
function 拡張子2contentType(url: string):string{
if(url.match(/\.htm(l?)$/)){return 'text/html'}
if(url.match(/\.css$/)){return 'text/css'}
return ''
}
async function fileExists(filePath: string): Promise<boolean> {
try {
await Deno.lstat(filePath);
return true;
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
return false;
}
throw err;
}
}
function ブラウザ起動(port: number){
Deno.run({cmd:['cmd', '/C start http://localhost:'+port]})
}
for(let port=49152; port<=65535 ;port++){
try{
const server = serve({ hostname: "0.0.0.0", port: port });
console.log(`HTTP webserver running. Access it at: http://localhost:` + port + `/`);
サーバ起動後(server)
}
catch(e){continue}
ブラウザ起動(port)
break
}
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>wawawa--</title>
<link rel="stylesheet" type="text/css" href="./css.css">
</head>
<body>
<p class=greenText>wowowo--</p>
</body>
</html>
view raw index.html hosted with ❤ by GitHub
実行結果


0 件のコメント:

コメントを投稿