Node.js 创建模块

mkdir /censorify
cd censorify

#建立主文件
vi censortext.js
var censoredWords = ["sad", "bad", "mad"];
var customCensoredWords = [];

function censor(inStr) {
    for(idx in censoredWords) {
        inStr = inStr.replace(censoredWords[idx], "****"); 
    }    
    for(idx in customCensoredWords) {
        inStr = inStr.replace(customCensoredWords[idx], "****"); 
    } 
    return inStr;
}

function addCensoredWord(word) {
       censoredWords.push(word); 
}

function getCensoredWords() {
       return censoredWords.concat(customCensoredWords);
}

exports.censor = censor;
exports.addCensoredWord = addCensoredWord;
exports.getCensoredWords = getCensoredWords;

#建立package.json(main指定入口)
vi package.json
{
    "author": "vfeelit@qq.com",
    "name": "censorify",
    "version": "0.1.1",
    "description": "",
    "main": "censortext",
    "dependencies": {},
    "engines": {
        "node": "*"   
     }
}

#打包(生成censorify-0.1.1.tgz文件)
npm pack

#在其它应用中安装
cd ../readwords
npm install ../censorify/censorify-0.1.1.tgz

#使用引入的包
vi readwords.js
var censor = require("censorify");

console.log(censor.getCensoredWords());
console.log(censor.censor("Some very sad, bad and mad text."));

censor.addCensoredWord("gloomy");
console.log(censor.getCensoredWords());
console.log(censor.censor("A very gloomy day."));

#运行结果
node readwords.js 
[ 'sad', 'bad', 'mad' ]
Some very ****, **** and **** text.
[ 'sad', 'bad', 'mad', 'gloomy' ]
A very **** day.