1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【備忘録】『JAVASCRIPTエンジニアのためのNODE.JS入門』の参考になった部分まとめ

Last updated at Posted at 2018-10-15

Node.jsに入門しています。気になる部分があればご指摘ください:joy:

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');
})
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?