LoginSignup
0
1

More than 5 years have passed since last update.

Node.jsをとりあえず動かしてみた

Last updated at Posted at 2018-03-12

前回の記事 の通り環境構築をしたので、
さっそくNode.jsを使って何かしら動かしてみた。

1. Node.jsでHello World!

下記のファイルを作成する。
vim hello.js

hello.js
var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World!');
}).listen(3000);

listenに指定するのはポート番号。
1024以下にする場合、root権限があれば実行できるが、
何かあった時にすべて乗っ取られて危険なのでやめておくべき。
※つまり、ポート番号80などを指定したい場合、工夫が必要。

2. hello.js 実行

下記コマンドを叩く。
node hello.js

ブラウザででアクセス。
例:http://153.126.204.61:3000/
Hello World!と表示される。

コンソールで [Ctrl] + [C] を押すと停止できる。

3. まとめ

nginxなどのWebサーバーを使わずとも、
ブラウザからのアクセスをNode.jsによって受け付け、
レスポンスを返すことが出来た。

ちなみに、systemctrl stop nginx でnginxを停止できる。
Webサーバーを止めていても、「hello.js」を動かしている間は、
ブラウザからのアクセスを受け付けられる。

0
1
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
0
1