博客
关于我
Node.js初体验
阅读量:798 次
发布时间: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/

你可能感兴趣的文章
NIFI1.21.0_NIFI和hadoop蹦了_200G集群磁盘又满了_Jps看不到进程了_Unable to write in /tmp. Aborting----大数据之Nifi工作笔记0052
查看>>
NIFI1.21.0通过Postgresql11的CDC逻辑复制槽实现_指定表多表增量同步_增删改数据分发及删除数据实时同步_通过分页解决变更记录过大问题_02----大数据之Nifi工作笔记0054
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_根据binlog实现数据实时delete同步_实际操作04---大数据之Nifi工作笔记0043
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_配置binlog_使用处理器抓取binlog数据_实际操作01---大数据之Nifi工作笔记0040
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_配置数据路由_实现数据插入数据到目标数据库_实际操作03---大数据之Nifi工作笔记0042
查看>>
NIFI从MySql中离线读取数据再导入到MySql中_03_来吧用NIFI实现_数据分页获取功能---大数据之Nifi工作笔记0038
查看>>
NIFI从PostGresql中离线读取数据再导入到MySql中_带有数据分页获取功能_不带分页不能用_NIFI资料太少了---大数据之Nifi工作笔记0039
查看>>
NIFI同步MySql数据_到SqlServer_错误_驱动程序无法通过使用安全套接字层(SSL)加密与SQL Server_Navicat连接SqlServer---大数据之Nifi工作笔记0047
查看>>
Nifi同步过程中报错create_time字段找不到_实际目标表和源表中没有这个字段---大数据之Nifi工作笔记0066
查看>>
NIFI大数据进阶_FlowFile拓扑_对FlowFile内容和属性的修改删除添加_介绍和描述_以及实际操作---大数据之Nifi工作笔记0023
查看>>
NIFI大数据进阶_NIFI的模板和组的使用-介绍和实际操作_创建组_嵌套组_模板创建下载_导入---大数据之Nifi工作笔记0022
查看>>
NIFI大数据进阶_NIFI监控的强大功能介绍_处理器面板_进程组面板_summary监控_data_provenance事件源---大数据之Nifi工作笔记0025
查看>>
NIFI大数据进阶_内嵌ZK模式集群1_搭建过程说明---大数据之Nifi工作笔记0015
查看>>
NIFI大数据进阶_外部ZK模式集群1_实际操作搭建NIFI外部ZK模式集群---大数据之Nifi工作笔记0017
查看>>
NIFI大数据进阶_离线同步MySql数据到HDFS_01_实际操作---大数据之Nifi工作笔记0029
查看>>
NIFI大数据进阶_离线同步MySql数据到HDFS_02_实际操作_splitjson处理器_puthdfs处理器_querydatabasetable处理器---大数据之Nifi工作笔记0030
查看>>
NIFI大数据进阶_连接与关系_设置数据流负载均衡_设置背压_设置展现弯曲_介绍以及实际操作---大数据之Nifi工作笔记0027
查看>>
NIFI数据库同步_多表_特定表同时同步_实际操作_MySqlToMysql_可推广到其他数据库_Postgresql_Hbase_SqlServer等----大数据之Nifi工作笔记0053
查看>>
NIFI汉化_替换logo_二次开发_Idea编译NIFI最新源码_详细过程记录_全解析_Maven编译NIFI避坑指南001---大数据之Nifi工作笔记0068
查看>>
NIFI集群_内存溢出_CPU占用100%修复_GC overhead limit exceeded_NIFI: out of memory error ---大数据之Nifi工作笔记0017
查看>>