编程语言
首页 > 编程语言> > 【第二届青训营-寒假前端场】- 「Node.js 与前端开发实战」笔记

【第二届青训营-寒假前端场】- 「Node.js 与前端开发实战」笔记

作者:互联网

将自己在掘金上发的笔记搬了过来:Node.js 与前端开发实战个人博客

本节课重点内容

Node.js 的应用场景(why)

Node.js运行时结构(what)

image.png

特点

编写Http Server (how)

安装Node.js

编写Http Server + Client, 收发GET, POST请求

Http Server

image.png

image.png

Http Client

const http = require('http');
const body = JSON.stringify({ msg: 'hello from my own client' });
// [url] [option] [callback]
const req = http.request('http://127.0.0.1:3000', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': body.length,
    },
}, (res) => {   // 响应体   
    const bufs = [];
    res.on('data', data => {
        bufs.push(data);
    });
    res.on('end', () => {
        const buf = Buffer.concat(bufs);
        const receive = JSON.parse(buf);
        console.log('receive json.msg is:', receive);
    });
})
req.end(body);

image.png

Promisify

可以用 Promise + async和await 重写这两个例子(why?)

await 关键字与异步函数一起使用时,它的真正优势就变得明显了 —— 事实上, await 只在异步函数里面才起作用。它可以放在任何异步的,基于 promise 的函数之前。它会暂停代码在该行上,直到 promise 完成,然后返回结果值。在暂停的同时,其他正在等待执行的代码就有机会执行了

async/await 让你的代码看起来是同步的,在某种程度上,也使得它的行为更加地同步。 await 关键字会阻塞其后的代码,直到promise完成,就像执行同步操作一样。它确实可以允许其他任务在此期间继续运行,但您自己的代码被阻塞。

image.png

编写静态文件服务器

编写一个简单的静态服务,接受用户发过来的http请求,拿到图片的url约定为静态文件服务器磁盘上对应的路径,再把具体内容返回给用户。这次除了 http 模块,还需要 fs 模块和 path 模块

先编写一个简单的 index.html,放于static目录下

image.png

static_server.js

const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
// __dirname是当前这个文件所在位置, ./为当前文件所在文件夹 folderPath即为static文件夹相对于当前文件路径
const folderPath = path.resolve(__dirname, './static');

const server = http.createServer((req, res) => {  // 注意这里的async
    // expected http://127.0.0.1:3000/index.html
    const info = url.parse(req.url);

    // static/index.html
    const filepath = path.resolve(folderPath, './'+info.path);
    console.log('filepath', filepath);
    // stream风格的api,其内部内存使用率更好
    const filestream = fs.createReadStream(filepath);
    filestream.pipe(res);
});
const port = 3000;
server.listen(port, () => {
    console.log(`server listens on:${port}`);
})

image.png

image.png

  1. CDN缓存+加速
  2. 分布式储存,容灾(服务器挂了也能正常服务)

编写React SSR服务

安装React

npm init
npm i react react-dom

编写示例

const React = require('react');
const ReactDOMServer = require('react-dom/server');
const http = require('http');
function App(props) {
    return React.createElement('div', {}, props.children || 'Hello');
}
const server = http.createServer((req, res) => {
    res.end(`
        <!DOCTYPE html>
        <html>
            <head>
                <title>My Application</title>
            </head>
            <body>
                ${ReactDOMServer.renderToString(
                    React.createElement(App, {}, 'my_content'))}
                <script>
                    alert('yes');
                </script>
            </body>
        </html>
    `);
})
const port = 3000;
server.listen(port, () => {
    console.log('listening on: ', port);
})

image.png

  1. 需要处理打包代码
  2. 需要思考前端代码在服务端运行时的逻辑
  3. 移除对服务端无意义的副作用,或重置环境

适用inspector进行调试、诊断

部署简介

写完了,如何部署到生产环境捏?

延伸话题

快速了解Node.js代码

Node. js Core贡献入门

编译Node.js

诊断/追踪

WASM, NAPI

总结感想

本节课从Node.js介绍起,实现了其编写Http Server的一个实战(并用Promise优化回调,还对SSR有了一定的了解),并在延伸话题里老师也给出了一些建议与拓展阅读,好欸~

本文引用的内容大部分来自欧阳亚东老师的课以及MDN。

标签:Node,http,res,js,青训营,const,server
来源: https://blog.csdn.net/qq_45890533/article/details/122673062