Node.js中也有一些功能的封裝,類似C#的類別庫,封裝成模組這樣方便使用,安裝之後用require()就能引入呼叫.
一、Node.js模組封裝
1.建立一個名為censorify的資料夾
2.在censorify下建立3個檔案censortext.js、package.json、README.md檔案
1)、在censortext.js下輸入一個過濾特定單字並用星號取代的函數。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | var censoredWorlds=[ "sad" , "bad" , "mad" ];
var custormCensoredWords=[];
function censor(inStr)
{
for (idx in censoredWorlds)
{
inStr=inStr.replace(censoredWorlds[idx], "****" );
}
for (idx in custormCensoredWords)
{
inStr=inStr.replace(custormCensoredWords[idx], "****" );
}
return inStr;
}
function addCensoreWorld(world)
{
custormCensoredWords.push(world);
}
function getCensoreWorlds()
{
return censoredWorlds.concat(custormCensoredWords);
}
exports.censor=censor;
exports.addCensoreWorld=addCensoreWorld;
exports.getCensoreWorlds=getCensoreWorlds;
|
登入後複製
2)、在package中設定清單資訊 例如版本 名稱和main指令等。
1 2 3 4 5 6 7 8 9 10 11 12 13 | {
"author" : "cuiyanwei" ,
"name" : "censority" ,
"version" : "0.1.1" ,
"description" : "Censors words out of text" ,
"main" : "censortext" ,
"dependencies" :{
"express" : "latest"
},
"enginee" :{
"node" : "*"
}
}
|
登入後複製
3)、建立的README.md檔案主要是描述說明
3.使用命令列建立封裝模組
使用命令列導航到censorify資料夾下,然後使用命令 npm pack 封裝產生tgz文件,這樣就封裝了一個模組。
![](http://files.jb51.net/file_images/article/201603/201636130756063.png?201636130756063)
二、封裝模組的使用
封裝模組的使用有兩種方法 :發佈到NPM註冊表、本地使用,這裡只記錄下本地使用的方法.
1.建立名readwords資料夾
2.命令列導航到readwords資料夾下,然後安裝已經封裝好的模組,如果是已經發佈到NPM註冊表的直接 npm install 名字,如果是在本地 npm install tgz檔案路徑。
![](http://files.jb51.net/file_images/article/201603/201636131622799.png?201636131622799)
3.安裝完成後會在readwords資料夾下產生包含censority子資料夾的node_modules資料夾
![](http://files.jb51.net/file_images/article/201603/201636131758272.png?201636131758272)
4.新建readwords.js檔案測試(注意程式碼console、封裝模組的函式別寫錯了)
1 2 3 4 5 6 | var censor= require ( "censority" );
console.log(censor.getCensoreWorlds());
console.log(censor.censor( "Some very sad,bad and mad text" ));
censor.addCensoreWorld( "gloomy" );
console.log(censor.getCensoreWorlds());
console.log(censor.censor( "A very goolmy day." ));
|
登入後複製
5.使用
用命令列node readwords.js來呼叫readwords.js查看結果
以上就是本文的全部內容,希望對大家的學習有所幫助。