Node
查找模块的顺序简单来讲,若是是
require('x')
这样开头不是相对or绝对地址符号,尾巴也没说是.js或者.json的,就当作模块来找。先找是否是core modul
e,而后一级一级向上看node_modules
文件夹,每一级的node_modules
先看里面是否有basename为所找的文件,再看是否有模块名文件夹下package.json
的main标明的文件,而后不死心地看看模块名文件夹下有没有index.js
和index.node
。最后找不到的话,还要搜一遍全局环境,好比$HOME/.node_modules/什么的。html
关于node.js的模块查找顺序require.resolve()node
module.exports vs exports
function hello() { console.log('Hello, world!'); } function greet(name) { console.log('Hello, ' + name + '!'); } module.exports = { hello: hello, greet: greet }; exports.hello = hello; exports.greet = greet;
可是你不能够直接对exports
赋值:json
// 代码能够执行,可是模块并无输出任何变量: exports = { hello: hello, greet: greet };
module.exports 初始值为一个空对象 {}数组
exports 是指向的 module.exports 的引用浏览器
require() 返回的是 module.exports 而不是 exports函数
exports
是引用 module.exports
的值。module.exports
被改变的时候,exports
不会被改变,而模块导出的时候,真正导出的执行是module.exports
,而不是exports
foo.jsui
exports.a = function(){ console.log('a') } module.exports = {a: 2} exports.a = 1
test.jsprototype
var x = require('./foo'); console.log(x.a) //2
module.exports
不能导出prototype建立的私有方法
foo.js线程
function View(){ } View.prototype.test = function(){ console.log('test') } View.test1 = function() { console.log('test1') } module.exports = View;
test.jscode
var x = require('./foo'); console.log(x) //{ [Function: View] test1: [Function] } console.log(x.test) //undefined console.log(x.test1) //[Function] x.test1() //test1
result
{ [Function: View] test1: [Function] } undefined [Function] test1
若是要输出一个键值对象{},能够利用exports
这个已存在的空对象{},并继续在上面添加新的键值;
若是要输出一个函数或数组,必须直接对module.exports
对象赋值。
因此咱们能够得出结论:直接对module.exports
赋值,能够应对任何状况
exports 和 module.exports 的区别
module.exports与exports??关于exports的总结
process
process
是Node.js
提供的一个对象,它表明当前Node.js
进程JavaScript
程序是由事件驱动执行的单线程模型,Node.js
也不例外。Node.js
不断执行响应事件的JavaScript函数,直到没有任何响应事件的函数能够执行时,Node.js
就退出了。
若是咱们想要在下一次事件响应中执行代码,能够调用process.nextTick()
:
// test.js // process.nextTick()将在下一轮事件循环中调用: process.nextTick(function () { console.log('nextTick callback!'); }); console.log('nextTick was set!');
用Node
执行上面的代码node test.js
,你会看到,打印输出是:
nextTick was set! nextTick callback!
这说明传入process.nextTick()
的函数不是马上执行,而是要等到下一次事件循环。
Node.js进程自己的事件就由process对象来处理。若是咱们响应exit事件,就能够在程序即将退出时执行某个回调函数:
// 程序即将退出时的回调函数: process.on('exit', function (code) { console.log('about to exit with code: ' + code); });
有不少JavaScript代码既能在浏览器中执行,也能在Node环境执行,但有些时候,程序自己须要判断本身究竟是在什么环境下执行的,经常使用的方式就是根据浏览器和Node环境提供的全局变量名称来判断:
if (typeof(window) === 'undefined') { console.log('node.js'); } else { console.log('browser'); }