1
0

More than 1 year has passed since last update.

【javascript】css を node.js のサーバで読む

Posted at

はじめに

Node.js でフロントエンド作りたいなー、と思い、勉強しています。
サーバ側のscript で html ファイルを読んで返したり、css を読んだりできるようになりました。

仕組みをわかっていないのですが、とりあえずメモしておきます。

内容

以下のようなファイル構成です。

├── app.js
├── css
│   └── test.css
└── index.html

app.js を node で起動してサーバにします。

$ node.js

ブラウザからlocalhost:8080 を見ると test.css で

が修飾されます。

サーバ側として

app.js
var http = require('http');
var fs = require('fs');

var server = http.createServer();
server.on('request', getCss);
server.listen(8080);
console.log('Server running …');

function getCss(req, res) {
  var url = req.url;
  console.log('url=', url)
  if ('/' == url) {
    fs.readFile('./index.html', 'UTF-8', function (err, data) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        res.end();
    });
  } else if ('/css/test.css' == url) {
    fs.readFile('./css/test.css', 'UTF-8', function (err, data) {
        console.log('test.css is read.')
        res.writeHead(200, {'Content-Type': 'text/css'});
        res.write(data);
        res.end();
    });
  }else{
    console.log('unexpected url...')
    res.writeHead(200, {
        "Content-Type": "text/html"
      });
      const responseMessage = "<h1>Hello World</h1>";
      res.end(responseMessage);
  }
}

としました。これ、結局、HTTP request が来た時のrouting を全て、require に設定した関数に書いています。こんな書き方していたら、たくさんURLがあったら大変な気もします。大規模になったら、きっと良い方法があるのでしょう。

読んで想像するに、
url が

  • '/' なら css.html を読んで、head を付けて HTTP responce にして返す
  • '/css/test.css' なら ./css/test.css を読んで、header を付けて HTTP responce にして返す

ようです。contents type が異なります。

用意している HTMLは

index.html
<html>
<head>
  <meta http-equiv="content-type" content="text/html charset=UTF-8">
  <title>css テスト</title>
  <link rel="stylesheet" type="text/css" href="./css/test.css">
</head>
<body>
  <div class="testclass">
    <p>ABCED</p>
  </div>
</body>
</html>

です。このheader で css を読む指定があります。そういうものなのか。

参考情報

参考にさせていただきました。感謝。

下記は読んでいないけれど、フォルダ構成とか参考にしたい。

まとめ

とりあえず、node.js で起動したサーバが側のjavascript で、CSSを読み込んだhtml を返すことができるようになった。

  • エラー処理をできるようになりたい
  • routing を app.js 以外に書くなど、コードを整理したい
  • python のときのように、logging を使いたい。console.log でなく

いろいろTODOはあるが。
(2022/10/28)

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0