いろいろやってみるにっき

てきとーに生きている奴の日記

古いエントリのサムネイル画像がリンク切れになってたりするけど、チマチマ修正中


WSL2のUbuntuにExpressをインストールして動かす

前回はXAMPPを入れたが、もっと簡単で軽い方法があることを思い出した。

 

 

Expressである。Node.jsがインストール済の環境なら数分でインストールできる。なお、この手順はUbuntu18.04以降であれば、実マシンでも仮想マシンでもWSLでも同じである。

 

Node.jsとnpmインストール

最新版をインストールする手順は下記の通り。

## updateしておく
$ sudo apt update -y

## Node.jsとnpmをインストール
$ sudo apt install -y nodejs npm

## n package を導入
$ sudo npm install n -g

## n package を使って node をインストール
$ sudo n stable

## n packeageを使ってnodeの最新版をインストール
$ sudo n stable

## 古いバージョンのNode.jsとnpmを削除
$ sudo apt purge -y nodejs npm
$ exec $SHELL -l

ここまでできたら再ログインか新しいTerminalの立ち上げ。

## バージョンの確認
$ node -v
v14.16.0
$ npm -v
6.14.11

 

Expressのインストールと起動

WSLではWindowsのフォルダ・ファイルとWSL上のLinuxのフォルダ・ファイルが全部見える。またWindows Terminalではデフォルトの起動ディレクトリは /mnt/c/Users/ Windowsのユーザ名 である。ここにインストールしてしまうと別のWSLで立てようとしたときに上書きしてしまう。複数起動する予定があるならばインストール先を決めておく。

## インストール先の作成
$ sudo mkdir "インストール先"

## インストール先への移動
$ sucd cd "インストール先"

 

 インストールは下記の通り。

## Expressのインストール
$ npx express-generator
npx: 10個のパッケージを2.432秒でインストールしました。
destination is not empty, continue? [y/N] y

   create : public/
   create : public/javascripts/
   create : public/images/
   create : public/stylesheets/
   create : public/stylesheets/style.css
   create : routes/
   create : routes/index.js
   create : routes/users.js
   create : public/index.html
   create : app.js
   create : package.json
   create : bin/
   create : bin/www

   install dependencies:
     $ npm install

   run the app:
     $ DEBUG=ttr:* npm start

$ npm install -g express-generator
npm notice created a lockfile as package-lock.json. You should commit this file.
added 53 packages from 36 contributors and audited 53 packages in 2.924s
found 0 vulnerabilities

 

Expressをインストールすると、デフォルトでは3000番ポートに設定されている。npxコマンドで表示された通り、bin/wwwファイルにある。normalizePort(process.env.PORT || '3000');の3000を別のポート番号に変更すればバッティングせずに起動できる。

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('ttr:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

 

Expressの起動は下記の通り。

## Expressの起動
$ npm start"

Terminalはロックされるので引き続きそのTerminalを使いたいのであれば末尾に&。

 

確認

ブラウザで http://localhost:3000 にアクセスする。

f:id:shigeo-t:20210314093028p:plain

インストール先は下記の通りなので、いじるなら下記のフォルダを触ればいい。

create : public/
create : public/javascripts/
create : public/images/
create : public/stylesheets/
create : public/stylesheets/style.css
create : routes/
create : routes/index.js
create : routes/users.js
create : public/index.html
create : app.js
create : package.json
create : bin/
create : bin/www

 

参考サイト

expressjs.com

 

 

お時間あったら、他のエントリもクリックして頂ければ幸いです。