隅歩つ

書いて理解を深める

Node.jsの「Hello World」

Node.jsは理解しておいたほうがいいですよね。

Node.jsがわかっているとWeb関連のことを理解しやすそう。

まずは、超基本から。

Node.jsの超基本

http、createServerを使って、ブラウザに「Hello Node.js」と表示させます。

const http = require('http');

let server = http.createServer((request, response) => {
    response.end('Hello Node.js');
});

server.listen(3000);
console.log('Server Start!');

ブラウザで表示させるとこんな↓感じ。

Node.jsの「Hello World」

Node.jsでHTMLを表示する

上の超基本の場合、HTMLを使っていないのでページを作るのが大変になってしまう。

HTMLを読み込む場合は、fs.readFile()を使います。

const http = require('http');
const fs = require('fs');

let server = http.createServer((req, res) => {
    fs.readFile('./index.html', 'utf-8', (error, data) => {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(data);
        res.end();
    });
});

server.listen(3000);
console.log('Server Start!');

ブラウザで表示させたのはこちら↓となります。

Node.jsの「Hello World」

これがNode.jsの「Hello World」になりますね。

ちなみに、HTMLはこちら↓です。

<!DOCTYPE html>
<html lang="en">
    <head>
       <meta charset="UTF-8" />
       <meta http-equiv="X-UA-Compatible" content="IE=edge" />
       <meta name="viewport" content="width=device-width, initial-scale=1.0" />
       <title>Hello Node.js</title>
   </head>
    <body>
        <h1>Hello Node.js</h1>
        <p>HTMLを表示する</p>
    </body>
</html>

Node.jsはなんかワクワクしますね。

yuuuha.hatenablog.com

yuuuha.hatenablog.com