preface

Do you often forget your NPM account and password? Do you have a headache when switching NPM accounts frequently? If you happen to have the above troubles, now install the Node tool Nucm, you can easily and quickly manage the NPM account.

Who will use itnucm

There are three types of people:

  • 1. People who often forget their NPM accounts and passwords
  • 2. People with multiple NPM accounts
  • 3. People who need to switch NPM accounts frequently

If you don’t log in to your NPM account regularly, it’s easy to forget your NPM account and password over time. If you have more than one NPM account, you are more likely to mess up your memory, and you may have to try your best to recall it every time you log in to your NPM account, and then enter and withdraw it multiple times. If our programmer’s memory is better than the average person, can remember the account password, but these accounts and passwords contain case and special symbols, each time the input needs to be particularly rigorous, can not enter a wrong character, or you can not log on. So anyway, we really need an NPM account management tool to manage these NPM account passwords that are rarely used. Nucm is especially popular because of its simple commands and practical functions. People who need nucM can now execute NPM install Nucm -g for installation and download.

nucmintroduce

Nucm can help you manage your NPM account information quickly and easily. Currently, only NPM source information is managed.

Nucm: Npm User Change Manager

Actually, nucM currently manages Access Tokens created by NPM account. Access Tokens can be simply understood as each NPM account can generate different types of release Tokens, which can be used to automate the release of NPM packages. Nucm mainly provides some simple operation commands to add and delete Access Tokens, view and switch them, and manage NPM accounts.

Access Tokens

An access token is an alternative to using your username and password for authenticating to npm when using the API or the npm command-line interface (CLI). An access token is a hexadecimal string that you can use to authenticate, and which gives you the right to install and/or publish your modules.

英 文翻译 :

Access tokens are an alternative to authenticating to NPM using your username and password when using API or NPM command line interface (CLI). An access token is a hexadecimal string that you can use for authentication and gives you the right to install and/or publish modules.

nucmCommon commands

Usage: nucm [options] [command]

Options:
  -v,--version                show version
  -h, --help                  display help for command

Commands:
  ls [options]                show account list
  use <name>                  switch account
  add <name> <access-tokens>  add account
  del <name>                  remove account
  localize <lang>             use localized languages
  install                     initialize
  help [command]              display help for command
Copy the code
The command describe
ls [options] Viewing the Account List
use <name> Switch account
add <name> <access-tokens> Add account
del <name> Remove the account
localize <lang> Use localized languages
install Initialize the

nucmThe project practice

At present, NUCM has been fully used in the daily work of the team. It can help me to quickly switch between my personal account and the team account, which is really praised by everyone. The following is a brief introduction to the basic operation steps for the first time.

Step 1: Install

$ npm install -g nucm # or YARN Global Add NUCm
Copy the code

After the installation is successful, execute nucm -V to verify whether the installation is successful (all understand).

Step 2: Add an account

1. Log in to the NPM account on the official website. In the upper right corner of the page, click Profile, and then click Access Token.

2. Click to generate a new tag.

3. Name your token

4. Select the type of access token (Publish)

5. Click generate token.

Copy the token from the top of the page.

7. Run nucm add


to add an account. Name is the name of the access-tokens copied in Step 6. Such as:

$nucm add Beezen XXXXXXXXXXXXXXXX The account is added successfullyCopy the code

Step 3: View the account list

Run nucm LS to check whether the newly added account appears in the account list, for example:

Desensitization is displayed by default$ nucm ls beezend -- xxxxxx...... xxxx beezen --- xxxxxx...... xxxx * beeze ---- xxxxxx...... xxxxDisplay a detailed list
$ nucm ls -l # or nucm ls --list

  beezend -- xxxxxxxxxxxxxxxxxxxxxxx
  beezen --- xxxxxxxxxxxxxxxxxxxxxxx
* beeze ---- xxxxxxxxxxxxxxxxxxxxxxx
Copy the code

Step 4: Switch accounts

Run nucm use

to switch to the specified account. Name is the name of the account finally added in the second step. Such as:

$nucm use Beezen has switched to account BeezenCopy the code

Step 5: Publish

Publish NPM with Access Tokens in step 4

Other auxiliary commands

1. Execute Nucm localize

to switch the localization language, such as English or Chinese, currently only support EN or CN. Such as:

$nucm localize EN Switched to language en cn $nucm localize en Switched to language enCopy the code

2. Run nucm del

to remove the added account. Such as:

$ nucm add beezen xxxxxxxxxx Add a new accountAccount added successfully $nucm del Beezen# Remove accountSucceeded in removing the accountCopy the code

3. Executing Nucm install will initialize the basic configuration contents in the ~/. Nucmrc configuration file. (Note: The nucM install command will be executed by default when the nucM package is installed globally for the first time, which generally does not need to be actively executed.)

$nucm install The NUCm is initialized successfullyCopy the code

Note: Currently, NucM only manages NPM source accounts. This function does not fail when switching to another source using NRM or other means.

Nucm source code analysis

Nucm is a CLI command line tool. Its main internal logic is to use the Commander NPM package to parse the parameters of commands entered on the console and execute the specified logic. The command execution logic of its setting is mainly to read and write the configuration information in ~/. Nucmrc file, and then to change the Access Token value corresponding to the account in ~/. NPMRC file, so as to achieve the purpose of switching accounts freely.

The project structure

The overall structure is relatively clear, with Chinese and English documents to facilitate the understanding of developers. All cli tool source code is from the bin file to start the execution, so we start from the bin/index,js file to read, and then from the directory structure can also be seen, the project is mainly to look at the bin/index.js each entry command corresponding to the action function logic. The following section is mainly to analyze the implementation logic of each action module, detailed steps will be annotated and analyzed.

. ├ ─ ─ CHANGELOG. Md# Version description├ ─ ─ LICENSE# Open Source License├ ─ ─ the README, md# English document├ ─ ─ README_CN, md# Chinese document├─ bin │ ├─ index.js# cli main entry├ ─ ─ package. JsonNPM package information├─ SRC │ ├─ Actions# Operation instruction│ │ ├ ─ ─ base. Js │ │ └ ─ ─ init. Js │ ├ ─ ─ index, js# Basic logic│ ├ ─ ─ langLocalize the description of the configuration file│ ├ ─ garbage ─ ├ ─ garbage# tools│ ├ ─ ├ ─ sci-1.txt ├ ─ sci-1.txt# lock
Copy the code

The main entrancebin/index.js

The main contents are as follows:

const program = require("commander");

const { getLangMessage } = require(".. /src/utils/index");
const { getUserList, changeUser, addUser, removeUser, changeLang } = require(".. /src/actions/base");
const { initInstall } = require(".. /src/actions/init");
const pkg = require(".. /package.json"); . program .command("ls")
  .option("-l,--list", getLangMessage("MSG_ls"))
  .description(getLangMessage("MSG_accountList")) .action(getUserList); .Copy the code

Using commander for command management helps decouple command configuration from logical execution. For example: when executing nucm ls, it will enter the above code logic program.command(“ls”) and execute the corresponding action method, and getUserList is the function logic finally executed by this command(will be analyzed later). GetLangMessage is an auxiliary method of encapsulation, primarily used for localized language translation of description content. The code is as follows:

/** * get internationalized language messages *@param MessageName indicates the messageName. It is primarily a tag that is used to read the specified message description from the configuration table. * /
function getLangMessage(messageName) {
  const config = require(".. /index").getConfig(); NPMRC 'file and' ~/.nucmrc 'file
  const langConfig = require(".. /lang/index"); // Localize the language configuration table
  const lang = (config.baseConfig && config.baseConfig.lang) || "en"; // Get the current language, only en and CN are available
  return langConfig[lang][messageName]; // Returns a localized description of the specified message name
}
Copy the code

The other changeUser, addUser, removeUser, changeLang and initInstall functions are all actions specified by the corresponding command. They are imported from files in the SRC/Actions/directory. Part of the key instructions will be analyzed below.

Basic instruction parsing

1. Nucm install: initialization instruction. Json: “Prepare “:” Nucm install”. The action function initInstall has very simple logic. It reads the configuration first. If the file does not exist or the basic configuration information in the file does not exist, it creates a file and writes the basic configuration information to the ~/. Nucmrc configuration file.

/** Initialize */
function initInstall() {
  const config = getConfig(); // Get the basic configuration
  if(! config.baseConfig) {// Check whether basic information exists in the configuration file
    config.nucmrcConfig.baseConfig = {
      lang: "en"}; fs.writeFileSync(config.nucmrc_path, ini.stringify(config.nucmrcConfig));// File contents are written
  }
  console.log(getLangMessage("MSG_initSuccess").green); // The success log is printed
}
Copy the code

2. Nucm LS: Obtain the user list. The action function is getUserList, and the main logic is to obtain the account information in the ~/. Nucmrc configuration file, and then arrange the display.

. Nucmrc configuration file content is as follows:

# ~/.nucmrc

[baseConfig]
lang=cn

[npm.beezend]
access-tokens=xxxxxxxxxxxxxxxxxxxxxx

[npm.beezen]
access-tokens=xxxxxxxxxxxxxxxxxxxxxx
is-current=true

[npm.beeze]
access-tokens=xxxxxxxxxxxxxxxxxxxxxx
Copy the code

Execute the following function:

// const nucmrcConfig = ini.parse(fs.readFileSync(nucmrc_path, "utf-8"));
// const npmAccountList = nucmrcConfig.npm; // List of NPM accounts
/ /...

/** * Get the user list */
function getUserList(options) {
  let npmAccountList = config.npmAccountList; // Get the account list from the configuration file
  let defaultLog = getLangMessage("MSG_getUserListDefaultLog"); // If there is no account, a log message is displayed by default
  let userList = Object.keys(npmAccountList)
    .map((key) = > {
      // According to nucm ls --list command, whether to add '--list' to determine whether desensitization
      let visibleToken = options.list
        ? npmAccountList[key]["access-tokens"]
        : desensitize(npmAccountList[key]["access-tokens"]); // Desensitization treatment
      if (npmAccountList[key]["is-current"]) {
        // The account whose IS-current field is true is the current active account
        return colors.green(` *${key} ${line(key, 10)} ${visibleToken}`);
      }
      return `  ${key} ${line(key, 10)} ${visibleToken}`;
    })
    .join("\n");
  console.log(userList || defaultLog.red); // Logs are printed
}
Copy the code

3. Nucm use

: Switch the account. The main work is to rewrite the value of field //registry.npmjs.org/:_authToken in the file.npmrc, and the flag bit of the activation account in the file.nucmrc.

/** * Change user *@param Name Account name */
function changeUser(name) {
  if(! isEnabeld())return; // Check whether the current function is active
  let npmAccountList = config.npmAccountList; // Get the account list
  let npmrcConfig = config.npmrcConfig; // Get.npmrc configuration information
  if(! npmAccountList[name]) {// The switchover account does not exist
    console.log(getLangMessage("MSG_accountNotFound").red);
    return;
  }
  if (npmrcConfig["//registry.npmjs.org/:_authToken"]) {
    // Assign to the special field '//registry.npmjs.org/:_authToken' in the.npmrc file. (NPM access token, which is concatenated after this field)
    npmrcConfig["//registry.npmjs.org/:_authToken"] =
      npmAccountList[name]["access-tokens"];
    // Rewrite the activation account flag in the.nucmrc configuration file as well
    Object.keys(npmAccountList).forEach((key) = > {
      if (npmAccountList[key]["is-current"]) {
        delete npmAccountList[key]["is-current"]; }}); npmAccountList[name]["is-current"] = true;
    // Real-time file write operation
    fs.writeFileSync(config.nucmrc_path, ini.stringify(config.nucmrcConfig));
    fs.writeFileSync(config.npmrc_path, ini.stringify(npmrcConfig));
    console.log(`${getLangMessage("MSG_accountChanged")} ${name}`.green); // The success log is printed}}Copy the code

4, Nucm add


and nucm del

: add and delete accounts. Action addUser and removeUser, respectively. Nucmrc file read and write, add and delete a data, see the following code:


/** Add user */
function addUser(name, token) {
  let npmAccountList = config.npmAccountList; // Get the account list! npmAccountList[name] && (npmAccountList[name] = {}); npmAccountList[name]["access-tokens"] = token; // Add the account and token
  fs.writeFileSync(config.nucmrc_path, ini.stringify(config.nucmrcConfig)); // File write
  console.log(getLangMessage("MSG_accountAddSuccess").green); // Prints logs
}

/** Remove user */
function removeUser(name) {
  let npmAccountList = config.npmAccountList; // Get the account list
  delete npmAccountList[name]; // Remove the account and token
  fs.writeFileSync(config.nucmrc_path, ini.stringify(config.nucmrcConfig)); // File write
  console.log(getLangMessage("MSG_accountRemoveSuccess").green); // Prints logs
}
Copy the code

The last

Nucm is really good to use! In the future plan, we will support the management of account information of non-NPM sources, and also adapt the official NPM login commands. Meanwhile, we will also focus on improving the overall interactive experience and the response efficiency of operations. Finally, welcome to Star + Fork + Watch for more valuable suggestions from the open source community.

Git project address: github.com/beezen/nucm