首頁  >  文章  >  web前端  >  node.js中的require使用詳解_node.js

node.js中的require使用詳解_node.js

WBOY
WBOY原創
2016-05-16 16:26:451805瀏覽

程式碼註解裡已經描述的非常的清晰,這裡就不多廢話了,直接奉上程式碼:

複製程式碼 程式碼如下:

/*在node中,可以使用require()函數來載入模組.
 * require函數使用一個參數,參數值可以帶有完整路徑的模組的檔名,也可以為模組名.當使用node中提供的模組時,在require函數中只需要指定模組名即可.
 * */
//建立一個頁面2.js;程式碼如下
var name="思思博士";
exports.name=name;
//建立一個頁面1.js;程式碼如下
var two=require("./2.js");
console.log(two.name);
//輸出結果:思思博士

/*
* 在node中所有的腳本檔案都是一個模組檔案,因此1.js也是一個模組檔案,又由於該檔案是在命令列視窗中透過node指令被直接運作的,因此在node中該模組檔案被定義為應用程式的主模組
 * 可以用以下的方法偵測出目前的模組是否是主模組
 * */
if(module===require.main){
    console.log("當前模組時主模組");
}
//輸出結果:當前模組時主模組

//2.js程式碼
var name="思思博士";
console.log(name);
exports.name=name;

//1.js程式碼:
var two=require("./2.js");
var two=require("./2.js");
//雖然引用了2次,但是只是執行了1次console.log(name)的輸出.

/*require.resolve(str)
 * 在node中,可以使用這個函數來查詢某個模組檔案的完整絕對路徑的檔案名稱.
 * */
var url=require.resolve("./2");
console.log(url);
//輸出結果:E:nodegys2.js

/*require.cache
 * 在node中,這個屬性代表了所有已載入模組的快取區.
 * */

var two=require("./2.js");
var cache=require.cache;
console.log(cache);
/*輸出結果:
 * { 'E:\node\gys\1.js':
 { id: '.',
 exports: {},
 parent: null,
 filename: 'E:\node\gys\1.js',
 loaded: false,
 children: [ [Object] ],
 paths:
 [ 'E:\node\gys\node_modules',
 'E:\node\node_modules',
 'E:\node_modules' ] },
 'E:\node\gys\2.js':
 { id: 'E:\node\gys\2.js',
 exports: { name: '思思博士' },
 parent:
 { id: '.',
 exports: {},
 parent: null,
 filename: 'E:\node\gys\1.js',
 loaded: false,
 children: [Object],
 paths: [Object] },
 filename: 'E:\node\gys\2.js',
 loaded: true,
 children: [],
 paths:
 [ 'E:\node\gys\node_modules',
 'E:\node\node_modules',
 'E:\node_modules' ] } }
 * */


//2.js程式碼
var name="思思博士";
console.log(name);
//1.js程式碼
//當使用delete關鍵字刪除快取區中快取的某個模組物件後,下次載入該模組時將重新執行該模組中的程式碼.使用程式碼:

var two=require("./2.js");
var two1=require("./2.js");
console.log("刪除前")
delete require.cache[require.resolve("./2.js")];
console.log("刪除後");
var two2=require("./2.js");
/*
 * 輸出結果:
 * 思思博士
 * 刪除前
 * 刪除後
 * 思思博士
 * */

小夥伴們是否清楚了node.js中require的使用方法了呢,如有疑問,請留言。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn