码迷,mamicode.com
首页 > Web开发 > 详细

nodejs

时间:2018-11-01 22:32:54      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:3.1   reac   adf   sage   xiaomi   second   The   ==   cond   


setTimeout(() => { //定时器
    console.log("3 seconds have passed");
}, 3000);

setInterval(function () { //延时循环
    console.log("2 seconds have passed")
}, 2000);

timer = setInterval(() => {
    console.log("2 seconds have passed")
}, 2000)
cleatInterval(timer)

console.log(__dirname);
console.log(__filename);

//回调函数
function  callFunction(fun, name) {
    fun(name);
}

callFunction(function(name) {
    console.log(name + ‘Bye‘);
}, ‘rails365‘);

//模块
//1----------
//count.js
var counter = function(arr) {
    return "There are " + arr.length + " elements in the array";
}

module.exports = counter;

//app.js
var counter = require(‘./count‘);
console.log(counter([‘ruby‘, ‘nodejs‘, ‘react‘]));

//2-------------
//count.js
var counter = function (arr) {
    return "There are " + arr.length + " elements in the array";
}

var adder = function (a, b) {
    return `the sum of the 2 numbers is ${a + b}`;
}
var pi = 3.14
module.exports.counter = counter;
module.exports.adder = adder;
module.exports.pi = pi;
//另一种写法
module.exports = {
    counter: counter,
    adder: adder,
    pi: pi
}

//app.js
var stuff = require(‘./count‘);
console.log(stuff.counter([‘ruby‘, ‘nodejs‘, ‘react‘]));
console.log(stuff.adder(3.2));
console.log(stuff.pi);
//end 模块------------

//事件
var events = require(‘events‘);//引入事件模块

var myEmitter = new events.EventEmitter();//创建事件对象

myEmitter.on(‘someEvent‘, function (message) {//事件对象监听‘someEvent‘事件
    console.log(message);
})
//手动触发‘someEvent‘事件,传递参数‘the event was emitted‘
myEmitter.emit(‘someEvent‘, ‘the event was emitted‘);

//============
var events = require(‘events‘);
var util = require(‘util‘);

var Person = function (name) {
    this.name = name
}

//令Person继承events.EventEmitter, 使Person有事件触发
util.inherits(Person, events.EventEmitter);

var xiaoming = new Person(‘xiaoming‘);
var lili = new Person(‘lili‘);
var lucy = new Person(‘lucy‘);

var person = [xiaoming, lili, lucy];

person.forEach(function(person) {
    person.on(‘speak‘, function(message) {
        console.log(person.name + " said:" + message);
    })
}
)
//end 事件--------

//读写文件(同步,异步)-----
var fs = require(‘fs‘);
//Sync同步,会阻塞,等待语句执行完成才往下执行
var readMe = fs.readFileSync("readMe.txt", "utf8");
console.log(readMe);

fs.writeFileSync("writeMe.txt", "write sting");
console.log("finished")

//2异步-----
var fs = require(‘fs‘);
//异步,线程遇到IO不阻塞,不进行IO操作,而是将其放入事件队列,且开辟了一个子线程处理事件队列中的事件,
//主线程继续向下执行语句,子线程对事件处理完毕了会通知主线程
var readMe = fs.readFile("readMe.txt", "utf8", function(err, data){
    console.log(data)
});

console.log("finished")

nodejs

标签:3.1   reac   adf   sage   xiaomi   second   The   ==   cond   

原文地址:https://www.cnblogs.com/ravener/p/9892597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!