【Node.js】Develop your own package!

Develop your own pack!
The basic structure of the initialization package
  • new folder. as the root directory of the package
  • In the folder, create three new files
    – package.json (package management configuration file)
    – index.js (package entry file)
    – README.md (package documentation)
  • Initialize package.json
{
    
    
    "name": "lusheng-pack",//包名,包名不能和网址里的包名重复
    "version": "1.0.0",//版本号
    "main": "index.js", //包的入口文件,导入根据main,找到index.js
    "description": "功能说明",//搜索包的时候的简短描述信息
	 "keywords": ["lusheng"],//搜索关键字,必须双引号,单引号报错
    "license": "ISC"//所遵循的开源许可协议,默认ISC
}
  • index.js
//包的入口文件,记录不同方法

//定义格式化时间的方法,传入日期时间
function getTime(time) {
    
    
    const dt = new Date(time)
    const y = 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}`
}
//定义补零函数
function padzero(n) {
    
    
    return n > 9 ? n : '0' + n
}
//定义转义HTML的方法,接收html
function gethtmlStr(Str) {
    
    
    return Str.replace(/<|>|"|&/g, (match) => {
    
    
        switch (match) {
    
    
            case '<':
                return '&lt;'
            case '>':
                return '&gt;'
            case '"':
                return '&quot;'
            case '&':
                return '&amp;'
        }
    })
}
//定义还原HTML的方法,接收转义语句
function sethtmlStr(Str) {
    
    
    return Str.replace(/&lt;|&gt;|&quot;|&amp;/g, (match) => {
    
    
        switch (match) {
    
    
            case '&lt;':
                return '<'
            case '&gt;':
                return '>'
            case '&quot;':
                return '"'
            case '&amp;':
                return '&'
        }
    })
}
//向外暴露的成员
module.exports = {
    
    
    getTime,
    gethtmlStr,
    sethtmlStr
}
page use
const pack = require("./index.js")
const str = `< h1 title='html语句'><span>转义啊?"&amp</span></h1>`
console.log(pack.gethtmlStr(str))
console.log(pack.sethtmlStr(pack.gethtmlStr(str)))

insert image description here

Modules can also be split as needed

insert image description here

  • index.js
//包的入口文件,记录不同方法
const DateTime = require("./until/getTime.js")
const htmlStr = require("./until/getStr.js")

//向外暴露的成员,
module.exports = {
    
    
  ...DateTime,
  ...htmlStr
}
Documentation for writing packages
  • User-friendly documentation for using your package
  • Generally contains 6 items
  • 1. Installation method
  • 2. Import method
  • 3. Format time
  • 4. Special attention points
  • 5. Open source agreement
release package
  • Register npm account, website address: https://www.npmjs.com/
  • Fill in account information, Full Name, Public Email, Username, Password
  • Click Create an Account to register
  • Log in to your email, click the verification link to verify your account
  • After registration, log in to the terminal
  • The npm address before each login has to be switched to the official server address, and the mirror address cannot be used.
  • npm install -g nrm
  • nrm use npm
  • Execute the npm login command, enter the user name, password, and email address in sequence, and the login is successful.
  • In the following situations, you have to go to the mailbox to get the verification code and enter it
    insert image description here
  • If this starts, the login is successful
    insert image description here
Publish the package on npm
  • Switch the terminal to the root directory and run the npm publish command to publish the package to npm (note: the package name cannot be the same)
  • cd root directory name
  • npm publish
remove published package
  • npm unpublish package name --force, you can delete, only delete within 72 hours,
  • With packages deleted in this way, republishing is not allowed within 24 hours
Module loading mechanism
  • Load from cache first
  • Modules are cached after the first load, which also means that require() will not cause the module's code to be executed multiple times
  • Whether it is a built-in module, a user-defined module, or a third-party module, they will be loaded from the cache first, thereby improving the loading efficiency of the module
Loading mechanism for built-in modules
  • Built-in modules have the highest loading priority
  • For example, when importing the built-in fs module, the custom module also has fs, but the priority of importing is the fs of the built-in module
Loading mechanism for custom modules
  • When loading a custom module, you must specify a path identifier starting with ./ or .../, if not specified, node will treat the custom module as a built-in module or a third-party module
  • When importing a custom module, if the extension of the file is omitted, node.js will try to load the following files in order
  • 1. Load according to the exact file name
  • 2. Complete the .js extension loading
  • 3. Complete the .json extension loading
  • 4. Complete the .node extension for loading
  • Failed to load, error
Loading mechanism for third-party modules
  • When it is neither a built-in module nor a custom module, node.js will start from the parent directory of the current module and try to find the /node_modules folder to load the third-party module. directory, look for node_modules
Loading mechanism when a directory is a module
  • 1. Find a file called package.json in the loaded directory, and look for the main attribute as the entry for require() loading
  • 2. When there is no package.json file or the main entry does not exist, node.js will load the index.js file in the directory
  • 3. If all fail, an error message will be printed and the missing module will be reported

Guess you like

Origin blog.csdn.net/weixin_44899940/article/details/129055178