コンテンツにスキップする

Node.jsでHello world!を表示する

投稿時刻2024年4月27日 16:27

Node.js

Node.jsでHello world!を表示します。
ターミナルで表示する場合とウェブサーバで表示する場合のコードを紹介します。

目次

ターミナルでHello world!を表示する

hello-world.terminal.jsというファイルを作成して、以下の内容をファイルに書き込みます。

console.log(`Hello world!`);

ターミナルで下記のコマンドを実行します。

$ node ./hello-world.terminal.js

以下のような実行結果が表示されます。

Hello world!

ウェブサーバでHello world!を表示する

hello-world.server.jsというファイルを作成して、以下の内容をファイルに書き込みます。

const http = require("http");

const hostname = `localhost`;
const port = 3000;

const server = http.createServer((req, res) => {
	res.statusCode = 200;
	res.setHeader(`Content-Type`, `text/plain`);
	res.end(`Hello World!`);
	return;
});

server.listen(port, hostname, () => {
	console.log(`Server running at http://${hostname}:${port}/`);
});

ターミナルで下記のコマンドを実行します。

$ node ./hello-world.server.js

以下のような実行結果が表示されます。

Server running at http://localhost:3000/

ウェブブラウザでhttp://localhost:3000/にアクセスすると、Hello world!と表示されます。

おわりに

Node.jsでHello world!を表示することができました。


参考記事