MENU

nodejs学习笔记1

July 26, 2020 • Read: 212 • Node.js

hello word

const http = require('http');
// 引入http库
const port = 8080;
// 设置监听端口

const server = http.createServer((req, res) => {
    // req: 请求路由
    // res: 返回数据
    res.end('Hello word');
    // 返回数据
});

server.listen(port, () => {
    // 这里用了一个匿名函数
    console.log('Server listening on: http://localhost:%s', port);
});

一次程序尝试:

const http = require('http')
const fs = require('fs')
const port = 8080

http.createServer((req, res) => {
    if (req.url == '/') {
        fs.readFile('./titles.json', (err, data) => {
            if (err) {
                console.error(err);
                res.end("Server Error");
            } else {
                const titles = JSON.parse(data.toString());
                fs.readFile('./template.html', (err, data) => {
                    if (err) {
                        console.error(err);
                        res.end("Server Error");
                    } else {
                        const tmpl = data.toString();
                        const html = tmpl.replace("%", titles.join("</li><li>"));
                        res.writeHead(200, { 'Content-Type': 'text/html' });
                        res.end(html);
                    }
                });
            }
        });
    }
}).listen(port, 'localhost');

创建中间件函数减少嵌套

/*
 * @Author: Mr.Sen
 * @LastEditTime: 2020-07-26 00:33:06
 * @Website: https://grimoire.cn
 * @Mr.Sen All rights reserved
 */
const http = require('http')
const fs = require('fs')
http.createServer((req, res) => {
    getTitles(res);
}).listen(8080, () => {
    console.log("Server Listening");
});

function getTitles(res) {
    fs.readFile('./titles.json', (err, data) => {
        if (err) {
            hadError(err, res);
        } else {
            getTemplate(JSON.parse(data.toString()), res);
        }
    });
}
function getTemplate(titles, res) {
    fs.readFile('./template.html', (err, data) => {
        if (err) {
            hadError(err, res);
        } else {
            formatHtml(titles, data.toString(), res);
        }
    });
}

function formatHtml(titles, tmpl, res) {
    const html = tmpl.replace('%', titles.join('</li><li>'));
    res.writeHead(200, {'Content-Type':'text/html'});
    res.end(html);
}

function hadError(err, res) {
    console.error(err);
    res.end("Server Error");
}

使用return 函数来减少嵌套

/*
 * @Author: Mr.Sen
 * @LastEditTime: 2020-07-26 00:52:13
 * @Website: https://grimoire.cn
 * @Mr.Sen All rights reserved
 */ 
const http = require('http')
const fs = require('fs');
const { format } = require('path');

http.createServer((req, res) => {
    getTitles(res);
}).listen(8080, () => {
    console.log('Listening on: http://localhost:8080');
});

function getTitles(res) {
    fs.readFile('./titles.json', (err, data) => {
        if (err) return hadError(err, res);
        getTemplate(JSON.parse(data.toString()), res);
    });
}

function getTemplate(titles, res) {
    fs.readFile('./template.html', (err, data) => {
        if (err) return hadError(err, res);
        formatHtml(titles, data.toString(), res);
    });
}

function formatHtml(titles, templ, res) {
    const html = templ.replace('%', titles.join('</li><li>'));
    res.writeHead(200, {'Content-Type':'text/html'});
    res.end(html)
}

function hadError(err, res) {
    console.error(err);
    res.end('Server Error');
}
Last Modified: July 27, 2020
Archives Tip
QR Code for this page
Tipping QR Code