3
2

More than 3 years have passed since last update.

npm と node.js のインストールから Hello World まで。

Last updated at Posted at 2020-07-23

Linux もしくは Windows Subsystem for Linux のターミナルから以下のコマンドを実行し、npm と node.js をインストールする。

   sudo sed -i -e 's%http://.*.ubuntu.com%http://ftp.jaist.ac.jp/pub/Linux%g' /etc/apt/sources.list
   sudo apt update
   sudo apt upgrade
   sudo apt-get install -y nodejs
   sudo apt install npm

任意のフォルダを作成し、その中で npm init コマンドを実行し package.json を作成する。
expressのパッケージをインストールし、アプリケーションのエントリーポイントとして app.js を作成する。

   mkdir hoge
   cd hoge
   npm init
   npm i express --save

   touch app.js

package.json の中身は次の通り。npm init の実行時になされる質問で main で指定するエントリーポイントをデフォルトから app.js に変更している。

{
  "name": "hoge",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Matsuoka",
  "license": "MIT",
  "dependencies": {
    "express": "^4.17.1"
  }
}

app.js の中身は次の通り。

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

const app = express();

app.use( function (req, res, next) {

    return res.send('こんにちは世界!');

});

let server = http.createServer(app);

server.listen('3000');

以下のコマンドで、node から app.js を実行する。

node app.js 

http://localhost:3000/ をブラウザで開く。

コメント 2020-07-24 003701.png

3
2
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
3
2