书名:SMASHING Node.js : JavaScript Everywherejavascript
原做者:(美)劳奇 Rauch.Gcss
译者:赵静java
出版日期:2014.1node
在浏览器中,全局对象指的是window
对象。在window对象上定义的全部内容(属性和函数)均可以被全局访问到。es6
setTimeout === window.setTimeout document === window.document
Node中的2个全局对象:npm
Node内置了不少实用的模块做为基础工具,包括http、net、fs等。api
Node摒弃了采用定义一堆全局变量的方式,转而引入了一个简单却强大无比的模块系统,该模块系统有3个核心的全局对象:require
、module
和exports
。浏览器
绝对模块是指Node经过在其内部node_modules查找到的模块,或者Node内置的如fs这样的模块。异步
require('http'); require('fs');
直接经过名字来require这个模块,无须添加路径名的,就是绝对模块。async
对于使用npm来安装的模块,例如安装colors模块,当安装完毕后,其路径就变成了./node_modules/colors
能够直接经过名称来require。
require('colors);
这种状况也是绝对模块。
相对模块是将require指向一个相对工做目录中的js文件。例如
require('./src/module_a'); require('./src/module_b');
在默认状况下,每一个模块都会暴露出一个空对象。能够使用exports来暴露对象的属性和函数。
// module_a.js exports.name = 'john'; exports.data = 'this is some data'; var privateVar = 5; exports.getPrivate = function(){ return privateVar; }
在main.js 中调用
var a = require('./src/module_a'); console.log(a.name); //john console.log(a.data); // this is some data console.log(a.getPrivate()); // 5
person.js
module.exports = Person; // 对module.exports重写 function Person(name){ this.name = name; } Person.prototype.talk = function(){ console.log('my name is' , this.name); }
main.js
var Person = require('./src/person'); var John = new Person('John'); John.talk(); // my name is John
在Node中事件的监听和分发使用EventEmit
,定义了on 、 emit、once等方法。
var EventEmitter = require('events'); var a = new EventEmitter(); a.on('event', function(){ console.log('event called.'); }); a.emit('event');
让自定义的类也能够使用事件监听,须要继承自EventEmitter。
修改person.js
module.exports = Person; function Person(name){ this.name = name; } const EventEmitter = require('events'); Person.prototype = new EventEmitter; Person.prototype.talk = function(){ console.log('my name is' , this.name); }
在main.js中调用
var Person = require('./src/person'); var John = new Person('John'); John.talk(); John.on('sleeping', function(){ console.log('sleeping called.') }); John.emit('sleeping');
const EventEmitter = require('events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', () => { console.log('an event occurred!'); }); myEmitter.emit('event');
Node中使用fs模块操做文件。
var fs = require('fs'); // 同步获取当前目录的文件列表 console.log(fs.readdirSync('.'));
var fs = require('fs'); // 异步的方式 function async(err, files){ console.log(files); } fs.readdir(__dirname, async);
process全局对象中包含了3个流对象,分别对应3个Unix标准流。
process.cwd(); // or __dirname
使用fs.watchFile 或fs.watch监视文件变化
var fs = require('fs'); function callBackFiles(err, files){ files.forEach(function(file){ // 监听后缀是css的文件 if(/\.css/.test(file)){ fs.watchFile(process.cwd() + '/' + file, function(){ console.log(' - ' + file + ' changed!'); }); } }); } var files = fs.readdir(process.cwd(), callBackFiles);
当修改index.css文件并保存后,控制台将输出。