Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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');
})
shimpeitakeda55
株式会社リスタでエンジニアをしています。 #swift #firebase #heroku #Node.js #React #Rails #Ruby
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした