Create a web server with Node.js

Create a web server with Node.js

Create server.js and index.html in the same folder. Then open a command line and type commands like node path / sever.js in that folder. Then open http: // localhost: 3000 / in your browser. Successful when connected to the local host.

sever.js

ar http = require('http'),
    port = 3000,//port number
    ipadress = 'localhost',//IPアドレス
    fs = require('fs');


var server = http.createServer();

server.on('request', function (req, res) {
    fs.readFile(__dirname + '/index.html', 'utf-8', function (err, data) {
        if (err) {
            res.writeHead(404, { 'Content-Type': 'text/plain' });
            res.write("not found!");
            return res.end();
        }
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(data);
        res.end();
    });
});

server.listen(port, ipadress);
console.log("server listening ...");

index.html

<!DOCTYPE html>
<html>

<head>
</head>

<body>
    Hello,world!
</body>

</html>

reference

Node.jsでサーバーを立ててngrokで外部公開

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事