MENU

nodejs学习笔记4

July 28, 2020 • Read: 132 • Node.js

nodejs学习笔记4

手写事件监听器

/*
 * @Author: Mr.Sen
 * @LastEditTime: 2020-07-28 16:47:45
 * @Website: https://grimoire.cn
 * @Mr.Sen All rights reserved
 */
var fs = require('fs');

fs.readFile('./hello.txt', { flag: 'r', encoding: 'utf8' }, (err, data) => {
    if (err) {
        console.log(err);
    } else {
        console.log(data);
        eventer.emit('readEnd', data);
    }
});

var eventer = {
    event: {

    },
    on: function (eventName, eventFn) {
        if (this.event[eventName]) {
            this.event[eventName].push(eventFn);
        } else {
            this.event[eventName] = [];
            this.event[eventName].push(eventFn);
        }
    },

    emit: function(eventName, eventMsg) {
        if (this.event[eventName]) {
            this.event[eventName].forEach(itemFn => {
                itemFn(eventMsg);
            });
        }
    }
}

eventer.on('readEnd', (eventMsg) => {
    console.log('find dio');
});

eventer.on('readEnd', (eventMsg) => {
    console.log('hou hou');
});

使用提供的event库

/*
 * @Author: Mr.Sen
 * @LastEditTime: 2020-07-28 16:53:15
 * @Website: https://grimoire.cn
 * @Mr.Sen All rights reserved
 */ 
var event = require('events');
var fs = require('fs');
var ee = new event.EventEmitter();

ee.on('hello', () => {
    console.log('file ended');
});

ee.on('hello', () => {
    console.log('kono jojo da!');
});


fs.readFile('./hello.txt', {encoding: 'utf8'}, (err, data) => {
    if (err) {
        console.log(err);
    } else {
        console.log(data);
        ee.emit('hello');
    }
});

使用promise对象封装

/*
 * @Author: Mr.Sen
 * @LastEditTime: 2020-07-28 17:05:32
 * @Website: https://grimoire.cn
 * @Mr.Sen All rights reserved
 */ 
var event = require('events');
var fs = require('fs');
var ee = new event.EventEmitter();

ee.on('hello', () => {
    console.log('file ended');
});

ee.on('hello', () => {
    console.log('kono jojo da!');
});

function readFiles(path) {
    return new Promise((resolve, reject) => {
        fs.readFile(path, {encoding:'utf8'}, (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
}

async function read(path) {
    var data = await readFiles(path);
    console.log(data);
    ee.emit('hello');  
}

read('./hello.txt');

path模块

var path = require('path');

// 输出后缀名
console.log(path.extname('dio.md'))

// 输出路径:D:\sex\name\age
console.log(path.resolve('/sex', 'name', 'age'));

// 输出路径:sex\name\age
console.log(path.join('sex', 'name', 'age'));

// 输出路径:d:\代码归档\七月\node\node2sex\name\age
console.log(__dirname + path.join('sex', 'name', 'age'));

// 输出当前文件绝对路径
console.log(__filename);
Archives Tip
QR Code for this page
Tipping QR Code