node学习系列之基础

400 查看

Node查找模块的顺序

简单来说,如果是require('x')这样开头不是相对or绝对地址符号,尾巴也没说是.js或者.json的,就当做模块来找。先找是不是core module,然后一级一级向上看node_modules文件夹,每一级的node_modules先看里面是否有basename为所找的文件,再看是否有模块名文件夹下package.json的main标明的文件,然后不死心地看看模块名文件夹下有没有index.jsindex.node。最后找不到的话,还要搜一遍全局环境,比如$HOME/.node_modules/什么的。

关于node.js的模块查找顺序require.resolve()

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赋值:

// 代码可以执行,但是模块并没有输出任何变量:
exports = {
    hello: hello,
    greet: greet
};

区别

  • module.exports 初始值为一个空对象 {}

  • exports 是指向的 module.exports 的引用

  • require() 返回的是 module.exports 而不是 exports

联系

exports是引用 module.exports的值。module.exports 被改变的时候,exports不会被改变,而模块导出的时候,真正导出的执行是module.exports,而不是exports
foo.js

 exports.a = function(){
  console.log('a')
 }

 module.exports = {a: 2}
 exports.a = 1 

test.js

 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.js

 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

processNode.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执行环境

有很多JavaScript代码既能在浏览器中执行,也能在Node环境执行,但有些时候,程序本身需要判断自己到底是在什么环境下执行的,常用的方式就是根据浏览器和Node环境提供的全局变量名称来判断:

if (typeof(window) === 'undefined') {
    console.log('node.js');
} else {
    console.log('browser');
}