以下内容来非常棒的讲解:Node JS Tutorial for Beginners,我已经爱上 The Net Ninja 的教程了!(PS:多图预警)
![](https://img.haomeiwen.com/i1632709/65835e3440606309.png)
![](https://img.haomeiwen.com/i1632709/43d93f4b7620fd28.png)
![](https://img.haomeiwen.com/i1632709/dc8462ad01383904.png)
![](https://img.haomeiwen.com/i1632709/21fa2f746dda812f.png)
![](https://img.haomeiwen.com/i1632709/3d3b3dee90b5b193.png)
![](https://img.haomeiwen.com/i1632709/0a0d9dc32f8e3605.png)
![](https://img.haomeiwen.com/i1632709/f865e4e235797c91.png)
Basic demos
var fs = require('fs');
/**
* 创建目录
*/
// 同步创建目录
// fs.mkdirSync('stuff');
// 异步创建目录
fs.mkdir('stuff', function() {
// 异步读取文件
fs.readFile('readMe.txt', 'utf8', function(err, data) {
// 异步写文件
fs.writeFile('./stuff/writeMe.txt', data);
});
});
/**
* 删除文件及目录
*/
// 删除已经存在的文件
fs.unlink('./stuff/writeMe.txt', function() {
// 异步删除目录
fs.rmdir('stuff');
// 同步删除目录
// fs.rmdirSync('stuff');
});
![](https://img.haomeiwen.com/i1632709/9a20ea45b60622e5.png)
var http = require('http');
var server = http.createServer(function(req, res) {
console.log('request was made: ' + req.url);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hey ninjas');
});
server.listen(3000, '127.0.0.1');
![](https://img.haomeiwen.com/i1632709/a56a46b37d95f9ec.png)
![](https://img.haomeiwen.com/i1632709/5cec5cb75b64d8dc.png)
![](https://img.haomeiwen.com/i1632709/1a8d52401a13a9b6.png)
![](https://img.haomeiwen.com/i1632709/83f0e5ac875c9d46.png)
![](https://img.haomeiwen.com/i1632709/3f53c2faaebd2548.png)
var http = require('http');
var fs = require('fs');
var myReadStream = fs.createReadStream(__dirname + '/readMe.txt', 'utf8');
var myWriteStream = fs.createWriteStream(__dirname + '/writeMe.txt');
myReadStream.on('data', function(chunk) {
console.log('new chunk received');
myWriteStream.write(chunk);
});
![](https://img.haomeiwen.com/i1632709/ac7fabbc0791109e.png)
var http = require('http');
var fs = require('fs');
var myReadStream = fs.createReadStream(__dirname + '/readMe.txt', 'utf8');
var myWriteStream = fs.createWriteStream(__dirname + '/writeMe.txt');
myReadStream.pipe(myWriteStream);
Pipes: don't have to manually listen for data events and we don't have to manually write to a write stream, it takes care all of that for us.
we can only use pipe method on Readable streams because we're piping from a Readable stream to a Writable stream. We can't pipe from a writable stream to a readable stream because we can't read from that.
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
console.log('request was made: ' + req.url);
res.writeHead(200, { 'Content-Type': 'text/plain' });
var myReadStream = fs.createReadStream(__dirname + '/readMe.txt', 'utf8');
myReadStream.pipe(res); // the response object is a writable stream
});
server.listen(3000, '127.0.0.1');
Serving HTML Pages
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
console.log('request was made: ' + req.url);
res.writeHead(200, { 'Content-Type': 'text/html' }); // modify Content-Type
var myReadStream = fs.createReadStream(__dirname + '/index.html', 'utf8');
myReadStream.pipe(res);
});
server.listen(3000, '127.0.0.1');
Serving JSON Data
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
console.log('request was made: ' + req.url);
res.writeHead(200, { 'Content-Type': 'application/json' }); // modify Content-Type
var myObj = {
name: 'Ryu',
job: 'Ninja',
age: 29
};
res.end(JSON.stringify(myObj)); // expects a string or a buffer
});
server.listen(3000, '127.0.0.1');
res.end()
expects a string or a buffer
Basic Routing
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
console.log('request was made: ' + req.url);
if (req.url === '/home' || req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.createReadStream(__dirname + '/index.html').pipe(res);
} else if (req.url === '/contact') {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.createReadStream(__dirname + '/contact.html').pipe(res);
} else if (req.url === '/api/ninjas') {
var ninjas = [{ name: 'ryu', age: 29 }, { name: 'yoshi', age: 32 }];
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(ninjas));
} else {
res.writeHead(404, { 'Content-Type': 'text/html' });
fs.createReadStream(__dirname + '/404.html').pipe(res);
}
});
server.listen(3000, '127.0.0.1');
Express
- basic
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('this is the homepage');
});
app.get('/contact', function(req, res) {
res.send('this is the contact page');
});
app.get('/profile/:id', function(req, res) {
res.send('You requested to see a profile with the id of ' + req.params.id);
})
app.listen(3000);
- Templage Engines
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.sendFile('index');
});
app.get('/contact', function(req, res) {
res.sendFile('contact');
});
app.get('/profile/:name', function(req, res) {
var data = { age: 20, job: 'ninja', hobbies: ['eating', 'fighting', 'fishing'] };
res.render('profile', { person: req.params.name, data }); // render profile view with person
})
app.listen(3000);
// profile.ejs
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<% include partials/nav.ejs %>
<h1>Welcome to the profile of <%= person %></h1>
<p>Age: <%= data.age %></p>
<p>Job: <%= data.job %></p>
<h2>Hobbies</h2>
<ul>
<% data.hobbies.forEach(function(item)){ %>
<li><%= item %></li>
<% }); %>
</ul>
</body>
</html>
- Static Files
app.use('/assets', express.static('assets'));
- Query Strings
app.get('/contact', function(req, res) {
res.render('contact', { qs: req.query });
});
- Handling Post Requests
var bodyParser = require('body-parser');
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.post('/contact', urlencodedParser, function(req, res) {
console.log(req.body); // { who: 'ryu', department: 'marketing', email: 'ninja@ninja.com' }
res.render('contact-success', { data: req.body });
});
网友评论