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>