Easily own your own bag

What is a package?

Third-party modules in Node.js are also called packages

Why do I need a bag?

  1. Because the built-in modules of Node.js provide only a few underlying API s, project development based on built-in modules is inefficient

  2. Packages are encapsulated based on built-in modules, providing a more advanced and convenient API, greatly improving development efficiency

  3. The relationship between packages and built-in modules is similar to that between jQuery and the browser's built-in API s

Classification of packages:

Project Package: A package introduced with require and installed in the project's node_modules directory.

The project package is divided into:

1. Development dependency packages: only used during development;Recorded at devDependencies node

2. Core dependency packages (production dependency packages): used both during development and after the project comes online;Recorded at dependencies node

Global Package: Exists from the command line and only a tool-like package is necessary for a global installation.

npm root -g  // See where packages are installed and how they are used

Next, let's develop our own package. The functions implemented are formatting dates, transferring special characters from HTML, and restoring special characters from HTML.

Easily own your own bag

A specification package, whose composition must meet the following three requirements:

1. Must exist as a separate directory (one package and one folder);

2. package.json must be included in the top-level directory of the package;

The package.json must contain three attributes: name, version, and main` (entry to the package);

Step 1: Initialize the package infrastructure

  1. Create a new itheima-tools folder as the root directory of the package

  2. In the itheima-tools folder, create the following three new files:

    • package.json (package management profile)

    • index.js (entry file for package)

    • README.md (package documentation)

Step 2: Initialize the package.json configuration file

npm init -y 
// Quickly create package.json

Step 3: Define a way to implement functionality in index.js

// The package's entry file index.js
​
// Functions that define formatting time
function dateFormat (dateStr) {
  const dt = new Date(dateStr)
​
  const y = padZero(dt.getFullYear())
  const m = padZero(dt.getMonth() + 1)
  const d = padZero(dt.getDate())
​
  const hh = padZero(dt.getHours())
  const mm = padZero(dt.getMinutes())
  const ss = padZero(dt.getSeconds())
​
  return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}
​
// Define a zero-complementing function
function padZero (n) {
  return n > 9 ? n : '0' + n
}
​
// Exposing required members
module.exports = {
  dateFormat
}
Test whether the code is working properly
// Test Code
​
const itheima = require('./flightloong-tools/index')
​
// Code for formatting time
const dtStr = itheima.dateFormat(new Date())
console.log(dtStr) // 2020-06-23 01:16:57

Define methods to escape HTML in index.js

// index.js
// Functions that define escape HTML characters
function htmlEscape(htmlstr) {
  return htmlstr.replace(/<|>|"|&/g, match => {
    switch (match) {
      case '<':
        return '&glt;'
      case '>':
        return '&gt;'
      case '"':
        return '&quot;'
      case '&':
        return '&amp;'
    }
  })
}
// test.js
​
const itheima = require('./flightloong-tools/index')
​
// Escape Html String
const htmlStr = '<h4 title="abc">This is h4 Label<span>123&nbsp;</span></h4>'
const str = itheima.htmlEscape(htmlStr)
console.log(str)

Define how to restore HTML in index.js

// Define functions to restore HTML characters
function htmlUnEscape(str) {
  return str.replace(/&glt;|&gt;|&quot;|&amp;/g, (match) => {
    switch (match) {
      case '&glt;':
        return '<'
      case '&gt;':
        return '>'
      case '&quot;':
        return '"'
      case '&amp;':
        return '&'
    }
  })
}
// Restore Html String
const resetHtml = itheima.htmlUnEscape(str)
console.log(resetHtml)

Step 4: Divide different modules

  1. Split the function of formatting time into SRC -> dateFormat.js

  2. Split the ability to handle HTML strings into SRC -> htmlEscape.js

  3. In index.js, import two modules to get the methods you need to share out

  4. In index.js, use module.exports to share the corresponding method

Step 5: Document the package

There is no mandatory requirement to specify what is written in the README file; as long as the role, usage, considerations, etc. of the package can be clearly described

The README.md document for the package we are creating now contains the following six items

  • Installation method

  • Import Method

  • Formatting time

  • Escape special characters in HTML

  • Restore special characters in HTML

  • Mozilla Public License

### install
```
npm i flightloong-tools
```
​
### Import
```js
const itheima = require('./flightloong-tools')
```
​
### Formatting time
```js
// Call dateFormat to format time
const dtStr = itheima.dateFormat(new Date())
// Results 2020-04-03 17:20:58
console.log(dtStr)
```
​
### Escape special characters in HTML
```js
// HTML string with conversion
const htmlStr = '<h1 title="abc">This is h1 Label<span>123&nbsp;</span></h1>'
// Call the htmlEscape method for conversion
const str = itheima.htmlEscape(htmlStr)
// The result of the conversion <h1 title="Abc"&Gt;This is the h1 label <Span>123&Nbsp;&Lt;/Span>&Lt;/h1>
console.log(str)
```
​
### Restore special characters in HTML
```js
// HTML string to restore
const str2 = itheima.htmlUnEscape(str)
// Output <h1 title="abc">This is the H1 label <span>123 </Span></h1>
console.log(str2)
```
​
### Mozilla Public License
ISC

Step 6: Register an npm account (there are already npm accounts to skip this step)

  1. Access ( npm ) Web site, click the sign up button to enter the registration user interface

  2. Fill in account information: Full Name, Public Email, Username, Password

  3. Click the Create an Account button to register an account

  4. Log in to your mailbox, click on the verification link, and verify your account

Step 7: Log into npm account

Note: Before running the npm login command, you must switch the server address of the downloaded package to the official server of npm. Otherwise, publishing the package will fail!

// View current mirror address
nrm ls 
// Switch to npm 
nrm use npm

After npm account registration is completed, you can execute npm login command in the terminal, enter user name, password, mailbox in turn, then log in successfully

Step 8: Publish the package to npm

After switching the terminal to the root directory of the package, run the npm publish command to publish the package to npm (note: package names cannot be the same)

Extension: Delete published packages

Remove published packages from npm by running the following command

npm unpublish Package Name --force 

Matters needing attention

  • The npm unpublish command can only delete packages published within 72 hours

  • Packets deleted by npm unpublish are not allowed to be republished for 24 hours

  • Be careful when publishing packages and try not to publish meaningless packages to npm!

Keywords: Javascript node.js

Added by tekrscom on Thu, 07 Oct 2021 19:53:01 +0300