按 ESC 概覽
brew install node
node -v
and npm -v
A piece of code is worth a thousand words.
var http = require('http');
http.createServer(function (req, res) {
res.statusCode = 200;// 304
res.end('fromHttpServer');
}).listen(5000);
In last week...
var http = require('http');
var host = '127.0.0.1';
http.createServer(function (req, res) {
console.log(req.method + ' ' + req.url + ' HTTP/' + req.httpVersion);
console.log('Host:' + host);
}).listen(5000, host);
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
var body =
'<html>'+
'<head>'+
'<title>An Example Page</title>'+
'</head>'+
'<body>'+
'Hello World, this is a very simple HTML document.'+
'</body>'+
'</html>'
res.setHeader('Content-Length', body.length);
res.end(body);
var port = 5000;
console.log('before calling http.createServer');
http.createServer(function (req, res) {
console.log(req.method + ' ' + req.url + ' HTTP/' + req.httpVersion);
res.end('ok');
}).listen(port, host, function () {
console.log('HTTP server started at ' + host + ':' + port);
});
console.log('http.createServer and .listen called');
However, they do provide synchronous versions. (postfixed with *Sync
)
var fs = require('fs');
fs.readFile('./package.json', function (err, data) {
if (err) { throw err; }
console.log('Your project name is ' + data.name + ' with keywords ' + data.keywords);
// console.log('---');
// console.log(data);
});
fs.readFile('./package.json', 'utf8', function (err, data) {
if (err) { throw err; }
res.setHeader('Content-Type', 'application/json');
res.end(data);
});
What if I want to add more routes?
Or output dynamic contents not just only simple length!
It's a mess!
npm install express@3.x.x --save
3.x.x is very IMPORTANTvar express = require('express');
require
works here?The Module System has three type of modules :
node_modules
folders : express, qAPI docs => express.js@3.x.x
npm install ejs
app.set('view engine', 'ejs');
.ejs
under views
directoryres.render
to generate HTMLinclude
<head>
<meta charset="utf-8">
<title><%= title %></title>
</head>
module.exports
to create controller moduleSo we have views
and controllers
, what about models
?
MySQL
or MongoDB
process.cwd