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

你可能感兴趣的文章
npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
查看>>
npm scripts 使用指南
查看>>
npm should be run outside of the node repl, in your normal shell
查看>>
npm start运行了什么
查看>>
npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
查看>>
npm 下载依赖慢的解决方案(亲测有效)
查看>>
npm 安装依赖过程中报错:Error: Can‘t find Python executable “python“, you can set the PYTHON env variable
查看>>
npm.taobao.org 淘宝 npm 镜像证书过期?这样解决!
查看>>
npm—小记
查看>>
npm介绍以及常用命令
查看>>
NPM使用前设置和升级
查看>>
npm入门,这篇就够了
查看>>
npm切换到淘宝源
查看>>
npm切换源淘宝源的两种方法
查看>>
npm前端包管理工具简介---npm工作笔记001
查看>>
npm包管理深度探索:从基础到进阶全面教程!
查看>>
npm升级以及使用淘宝npm镜像
查看>>
npm发布包--所遇到的问题
查看>>
npm发布自己的组件UI包(详细步骤,图文并茂)
查看>>
npm和package.json那些不为常人所知的小秘密
查看>>