博客
关于我
Node.js初体验
阅读量:794 次
发布时间:2023-02-16

本文共 4573 字,大约阅读时间需要 15 分钟。

Node.js异步处理与事件驱动模式

前言

刚刚阅读了《Node.js入门》,参考node官网和一些相关文章,感觉与Node.js更亲近了一步。迫不及待想写篇文章分享,希望读者能读完后获益良多。

应用目标

• 用户可以通过浏览器使用我们的应用。

• 当用户提交文件时,看到一个欢迎页面,包含一个文件上传表单。

• 用户选择图片提交后,图片将上传到服务器,并在页面上显示。

实现思路

首先,搭建Node.js服务器。Node.js可以通过http模块轻松创建服务器。创建路由模块,将不同请求路由到相应的处理程序。

应用实现

运行Node.js

创建一个简单的helloworld.js文件:

console.log("Hello World");

在终端运行:

node helloworld.js

输出:Hello World

创建服务器

创建server.js文件:

var http = require("http");http.createServer(function(request, response) {    response.writeHead(200, {"Content-Type": "text/plain"});    response.write("Hello World");    response.end();}).listen(8888);console.log("Server has started.");

运行:

node server.js

输出:Server has started.

加入路由

创建router.js:

function route(handle, pathname) {    console.log("About to route a request for " + pathname);    if (typeof handle[pathname] === 'function') {        handle[pathname]();    } else {        console.log("No request handler found for " + pathname);    }}module.exports = route;

创建requestHandlers.js:

function start() {    console.log("Request handler 'start' was called.");}function upload() {    console.log("Request handler 'upload' was called.");}module.exports = { start, upload };

创建index.js:

var server = require("./server");var router = require("./router");var requestHandlers = require("./requestHandlers");var handle = {};handle["/"] = requestHandlers.start;handle["/upload"] = requestHandlers.upload;server.start(router.route, handle);

运行:

node index.js

输出:Server has started.

异步处理

阻塞响应

修改requestHandlers.js:

function start() {    console.log("Request handler 'start' was called.");    function sleep(milliSeconds) {        var startTime = new Date().getTime();        while (new Date().getTime() < startTime + milliSeconds) {}    }    sleep(10000);    return "Hello Start";}function upload() {    console.log("Request handler 'upload' was called.");    return "Hello Upload";}module.exports = { start, upload };
非阻塞响应

修改server.js:

var http = require("http");var url = require("url");function start(route, handle) {    function onRequest(request, response) {        var pathname = url.parse(request.url).pathname;        console.log("Request for " + pathname + " received.");        response.writeHead(200, {"Content-Type": "text/plain"});        var content = route(handle, pathname, response);        response.write(content);        response.end();    }    http.createServer(onRequest).listen(8888);    console.log("Server has started.");}module.exports = start;

修改route.js:

function route(handle, pathname, response) {    console.log("About to route a request for " + pathname);    if (typeof handle[pathname] === 'function') {        handle[pathname](response);    } else {        console.log("No request handler found for " + pathname);        response.writeHead(404, {"Content-Type": "text/plain"});        response.write("404 Not found");        response.end();    }}module.exports = route;

修改requestHandlers.js:

function start(response) {    console.log("Request handler 'start' was called.");    var content = "empty";    var exec = require("child_process").exec;    exec("find /", { timeout: 10000, maxBuffer: 20000 * 1024 }, function (error, stdout, stderr) {        content = stdout;        response.writeHead(200, {"Content-Type": "text/plain"});        response.write(content);        response.end();    });}function upload(response) {    console.log("Request handler 'upload' was called.");    response.writeHead(200, {"Content-Type": "text/plain"});    response.write("Hello Upload");    response.end();}module.exports = { start, upload };

运行:

node index.js

文件上传

使用formidable模块:

var formidable = require('formidable');var http = require('http');var fs = require('fs');http.createServer(function(req, res) {    if (req.url === '/upload' && req.method.toLowerCase() === 'post') {        var form = new formidable.IncomingForm();        form.parse(req, function(err, fields, files) {            fs.readFile(files.upload.path, 'binary', function(err, file) {                if (err) {                    res.writeHead(500, {"Content-Type": "text/plain"});                    res.write(err + '\n');                    res.end();                } else {                    res.writeHead(200, {"Content-Type": "image/png"});                    res.write(file, 'binary');                    res.end();                }            });        });        return;    }    res.writeHead(200, {"Content-Type": "text/html"});    res.end('
');}).listen(8888);console.log("Server has started.");

结语

通过以上步骤,我们成功创建了一个异步处理的文件上传应用。Node.js的异步特性使得服务器能够高效处理大量请求,适合构建高性能的网络应用。

转载地址:http://mpjfk.baihongyu.com/

你可能感兴趣的文章
NLog类库使用探索——详解配置
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
NLP 模型中的偏差和公平性检测
查看>>
Vue3.0 性能提升主要是通过哪几方面体现的?
查看>>
NLP 项目:维基百科文章爬虫和分类【01】 - 语料库阅读器
查看>>
NLP_什么是统计语言模型_条件概率的链式法则_n元统计语言模型_马尔科夫链_数据稀疏(出现了词库中没有的词)_统计语言模型的平滑策略---人工智能工作笔记0035
查看>>
NLP、CV 很难入门?IBM 数据科学家带你梳理
查看>>
NLP三大特征抽取器:CNN、RNN与Transformer全面解析
查看>>
NLP入门(六)pyltp的介绍与使用
查看>>
NLP学习笔记:使用 Python 进行NLTK
查看>>
NLP度量指标BELU真的完美么?
查看>>
NLP的不同研究领域和最新发展的概述
查看>>
NLP的神经网络训练的新模式
查看>>
NLP采用Bert进行简单文本情感分类
查看>>
NLP问答系统:使用 Deepset SQUAD 和 SQuAD v2 度量评估
查看>>
NLP项目:维基百科文章爬虫和分类【02】 - 语料库转换管道
查看>>
NLP:从头开始的文本矢量化方法
查看>>
NLP:使用 SciKit Learn 的文本矢量化方法
查看>>
NLTK - 停用词下载
查看>>
nmap 使用总结
查看>>