分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

node.js中events模块应用

发布时间:2023-09-06 02:03责任编辑:赖小花关键词:js

将readFile封装成一个方法(解决异步问题)

原因:因为node.js是非阻塞I/O,所以是异步的,读文件是I/O请求,所以会被抛出,等所有的非I/O请求都完成后才会进行

有异步问题的代码:

var fs = require("fs");function fnReadFile(file){ ???fs.readFile(file, function(err, data){ ???????return data; ???});}console.log(fnReadFile("hei.txt"));//输出undefined 原因fs.readFile方法是异步的

解决 方法一:回调函数

var fs = require("fs");function fnReadFile(file, callback){ ???fs.readFile(file, function(err, data){ ???????callback(data.toString()); ???});}fnReadFile("hei.txt", function(res){ ???console.log("读取的数据是:" + res);});

方法二:events模块 监听on 广播emit

var events = require("events");var fs = require("fs");var myEvent = new events();myEvent.on("showData", function(str){ ???????console.log("读取的数据是:" + str);});function fnReadFile(file){ ???????fs.readFile(file, function(err, data){ ???????????????myEvent.emit("showData", data); ???????});}fnReadFile("hei.txt");

node.js中events模块应用

原文地址:https://www.cnblogs.com/luowenshuai/p/9293691.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved