---
title: "创建nodejs模块并发布到npm包管理平台"
author: "becomeBetter"
date: "2016-05-23T12:05:26Z"
tags: []
categories: ["开源软件"]
slug: "nodejs-npm"
draft: false
lastmod: "2016-05-23T12:05:25Z"
id: 2299953
url: "https://becomebetter.iteye.com/blog/2299953"
---

安装好nodejs后，npm也自动被安装了，首先配置npm，填写作者信息:

```
npm set init.author.name "Kean Yuan"
npm set init.author.email "yuanzuochao@gmail.com"
npm set init.author.url "http://becomebetter.iteye.com/"
```

 接下来在github创建一个仓库scapegoat\_tt，然后clone到本地，并进入该目录

```
git clone git@github.com:brentertz/scapegoat_tt.git
cd scapegoat_tt
```

 进入目录后执行

```
npm init
```

 会在目录下生成package.json文件

```
{
  "name": "scapegoat_tt",
  "version": "1.0.0",
  "description": " an npm module consisting of a couple utility methods for escaping and unescaping HTML entities – commonly needed utils to prevent XSS attacks when rendering user generated content",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/becomeBetter/scapegoat_tt.git"
  },
  "keywords": [
    "escape"
  ],
  "author": "Kean Yuan <yuanzuochao@gmail.com> (http://becomebetter.iteye.com/)",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/becomeBetter/scapegoat_tt/issues"
  },
  "homepage": "https://github.com/becomeBetter/scapegoat_tt#readme"
}
```

 

然后编写index.js文件

```
/**
 * Escape special characters in the given string of html.
 *
 * @param  {String} html
 * @return {String}
 */
module.exports = {
  escape: function(html) {
    return String(html)
      .replace(/&/g, '&amp;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;');
  },

  /**
   * Unescape special characters in the given string of html.
   *
   * @param  {String} html
   * @return {String}
   */
  unescape: function(html) {
    return String(html)
      .replace(/&amp;/g, '&')
      .replace(/&quot;/g, '"')
      .replace(/&#39;/g, ''')
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>');
  }
};
```

 在[https://www.npmjs.com](https://www.npmjs.com/)注册一个账号，然后用npm adduser命令在本地添加账号

最后用npm publish命令就可以发布了