美文网首页
NodeJS基础篇

NodeJS基础篇

作者: 一个笑点低的妹纸 | 来源:发表于2018-05-02 23:46 被阅读11次

以下内容来非常棒的讲解:Node JS Tutorial for Beginners,我已经爱上 The Net Ninja 的教程了!(PS:多图预警)

Node.js ACTUALLY is... Why is Node.js so Popular? What We'll Learn... JavaScript Engine Machine Code So... Node.js with V8

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');
});
Response Headers
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');
Buffers So... Streams Streams in Node.js Streams
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);
});
Pipes
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

  1. 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);
  1. 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>
  1. Static Files
app.use('/assets', express.static('assets'));
  1. Query Strings
app.get('/contact', function(req, res) {
    res.render('contact', { qs: req.query });
});
  1. 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 });
});

相关文章

网友评论

      本文标题:NodeJS基础篇

      本文链接:https://www.haomeiwen.com/subject/rlxxlftx.html