nodejs
Posted ravener
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nodejs相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
javascript 用于在节点#nodejs #javascript内设置react app的代码片段