とある科学の備忘録

とある科学の備忘録

CやPythonのプログラミング、Arduino等を使った電子工作をメインに書いています。また、木製CNCやドローンの自作製作記も更新中です。たまに機械学習とかもやってます。

【Ubuntu】Node.jsのインストールと使い方

UbuntuでNode.jsサーバーを動かしてみます。

動作環境はこちら:
f:id:pythonjacascript:20210409235433p:plain

Node.jsとは

  • JavaScriptを用いたサーバーサイドの実行環境です。
  • Chrome's V8 JavaScript engineを用いており、比較的高速に動作する
  • モジュール管理にnpm(Node Package Manager)を使う。インストールや削除などが簡単に行える。
    • インストールだと `npm install [hoge]` 、削除する場合は `npm uninstall [hoge] `

まあ詳しい話は公式サイトなどを参考に↓
nodejs.org


環境構築とバージョン確認

以下のコマンドを実行するだけ

$ sudo apt update
$ sudo apt install nodejs
$ sudo apt install npm

インストールできたかどうか確認

$ npm --version 
6.14.4

$ node --version             
v10.19.0

Hello World()

適当なディレクトリにいって、

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

http.createServer(function (req, res) {
  console.log("New Access!!");
  console.log("URL: " + req.url);
  console.log("Method: " + req.method);

  switch (req.url) {
    case "/":
      fs.readFile("./index.html", function (err, data) {
          res.writeHead(200, { "Content-Type": "text/html" });
          res.write(data);
          res.end();
      });
      break;
    case "/style.css":
      fs.readFile("./style.css", function (err, data) {
          res.writeHead(200, { "Content-Type": "text/css" });
          res.write(data);
          res.end();
      });
      break;
  }
}).listen(8000);


上のファイルをmain.jsのような名前で保存します。


同様のディレクトリにindex.htmlとstyles.cssも作成します。

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="./style.css" />
    <title>Hello</title>
  </head>
  <body><h1>Hello Node.js!</h1><p>This is index.html</p></body>
</html>
body {
	width: 100%;
    background-color: #b00;
    color:#fff;
}


そして、

$ node main.js

を実行するとサーバーが起動します。「ブラウザで 127.0.0.1:8000/」にアクセスすると以下のように表示されます。

f:id:pythonjacascript:20210420211656p:plain


Hello World(express編)

expressとは、Node.jsの中でおそらく一番使われているWebフレームワークです。
expressjs.com

以下のようなファイルでmain2.jsを作ります。

// $ npm install express # これをJS実行前に実行して、Expressをインストールする。-gをつけるとグローバルにインストールされます。

var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');
var app = express();

//ミドルウェアの設定:
//すべてのリクエストに対応するapp.get(), app.post()が呼ばれる前にこの関数が実行される。
//next()関数が呼ばれるとapp.get(), app.pos()が呼ばれる。
app.use(function(req, res, next){
  console.log("New access " + req.method + "\t" + req.url);
  next();
});

app.get('/home', function(req, res) {
  res.type('text/html').send(`<h1>This is home!!</h1><p><a href="/">open index.html</a></p>`)
});


app.get('/', function(req, res) {
    fs.readFile("./index.html", function (err, data) {
        res.writeHead(200, { "Content-Type": "text/html" });
        res.write(data);
        res.end();
    });
});

app.get('/style.css', function(req, res) {
  fs.readFile("./style.css", function (err, data) {
      res.writeHead(200, { "Content-Type": "text/css" });
      res.write(data);
      res.end();
  });
});

app.get('/redirect', function(req, res) {
  res.redirect("/home");
});


app.get('/form', function(req, res) {
  res.type('text/html').send(`
    <!DOCTYPE html>
    <html>
      <head><title>Form sample</title></head>
      <body>
        <h1>Form sample</h1>
        <form action="/post" method="POST">
          <input type="text" name="text1"><br>
          <input type="text" name="text2">
          <input type="submit" value="送信">
        </form>
      </body>
    </html>
  `)
});

app.post('/post',function(req, res, next){
  console.log(req.body);
  res.send(req.body);
});

app.listen(8000); //8000ポートを開く

また、index.htmlとstyles.cssも前節で書いたものをコピペしてきます。


そして、実行するには以下のコマンドを実行します。

$ npm install express #expressをインストール
# ↑のコマンドだと、現在いるフォルダに node_modules フォルダが作成されて、その中にインストールされる。
# グローバルにインストールするには、npm install -g expressのように -g をつける必要がある。
$ node main2.js

以下の場所にアクセスできます。

URI 説明
localhost:8080/ index.htmlを表示
localhost:8080/home JSに埋め込んであるHTML文字列を表示
localhost:8080/redirect/ /homeにリダイレクトします。
localhost:8080/form 2つのテキストボックスに文字列を入力して送信するとサーバーにデータが送られる。


gitignoreの書き方

以下のファイルはgitで管理する必要がありません。

ファイル名 説明
--- ---
node_modules npm installでインストールしたNpde.jsのモジュールが入っています。
package-lock.json npm install でインストールしたモジュール情報が記載されています。**手動で編集してはいけない!!!**