02/18/2020
NodeJS
参考资料
基础
npm安装
npm install npm -g
npm install express
npm install fs
npm install events
-g表示全局下载,没有表示下载到本地文件夹
初始化package.json
npm init
创建package.json 文件
{
"name": "hello",
"version": "1.0.0",
"description": "",
"main": "index.js", //<-----main 函数
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1" //<---- 脚本,npm run test 等于执行 echo \"Error: no test specified\" && exit 1
},
"author": "",
"license": "ISC",
"dependencies": {
//<----模块
"events": "^3.2.0"
}
}
导入模块
var events = require('events'); #原生模块
var fs = require('fs')
var hello = require('./hello.js') #相对路径的文件模块
回调函数
非阻塞I/O代码
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("程序执行结束!");
>程序执行结束!
>输出data
事件驱动程序–观察者模式
绑定/注册事件 On/AddListener
var events = require('events');
var emitter = new events.EventEmitter();
emitter.on('someEvent', function(arg1, arg2) {
console.log('listener1', arg1, arg2);
});
emitter.on('someEvent',