Node.jsに入門しています。気になる部分があればご指摘ください
readFileメソッドは非同期で動作する
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
fs.readFile('./temp.html', 'utf-8', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
})
});
server.listen(1234);
console.log('start server');
静的ファイルの供給にはストリームの pipe メソッドを使う
var http = require('http');
var fs = require('fs');
var url = require('url');
var server = http.createServer(function(req, res) {
var urlParts = url.parse(req.url);
var path = __dirname + '/' + urlParts.pathname;
var stream = fs.createReadStream(path);
stream.pipe(res)
});
server.listen(1234);
console.log('start server');
express を使った実装
var express = require('express');
var ejs = require('ejs');
var bodyParser = require('body-parser');
var app = express();
app.engine('ejs', ejs.renderFile);
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', function(req, res) {
console.log('---GET Reqest---');
console.log('name is ' + req.query.name);
console.log('age is ' + req.query.age);
res.render('temp.ejs', {});
});
app.post('/', function(req, res) {
console.log('---POST Request---');
console.log('name is ' + req.body.name);
console.log('age is ' + req.body.age);
res.render('temp.ejs', {});
});
var server = app.listen(1234, function() {
console.log('start server');
})