在node.js中使用require()函数有哪些不同的方法?

时间:2016-11-17 13:01:41

标签: javascript node.js

我们可以在Node.js中使用require()函数的不同方法有哪些 他们之间有什么区别? 例如,

  • const colors = require('colors');我知道,这会查找node_modules目录中的包
  • const colors = require('./colors');
  • const colors = require('/colors');
  • const Datastore = require('@google-cloud/datastore');

  • const square = require('lib').square;

  • const ep = require('./routes')(app);
  • const { red, blue, pink } = require('colors');
  • 还包括其他类型的用法,不在上面的列表中。

1 个答案:

答案 0 :(得分:1)

要求(' ./ colors')在文件所在的同一文件夹中查找colors.js。 在大多数其他情况下,您列出的参数只是文件的路径。

接下来与需求行为无关

const square = require('lib').square; //is same as
const lib = require('lib');           //1. get lib object
const square = lib.square             //2. access its property 

const ep = require('./routes')(app);    //is same as
const routesFunc = require('./routes'); //1. in routes file exports object is function
const ep = routesFunc(app);             //2.execute function with parameter

const { red, blue, pink } = require('colors'); // same as previous
const colors = require('colors);               //looks for color in node modules and returs colors object
const {red, blue, pink} = colors;              //es6 feature. Same as 
const red = colors.red;
const blue = colors.blue; 
const pink = colors.pink