search
HomeWeb Front-endJS TutorialHow to use Nodejs to publish npm packages and make them into command line tools

This time I will show you how to use Nodejs to publish npm packages and make them into command line tools. What are the precautions?. Here are the practical cases. Let’s take a look.

<span>近日当我在使用npm上已经存在的一个包时,发现它有bug;于是决定自己实现这个功能,自己写一个npm包。</span>

Let me record my implementation process.

1. npm init

Select a folder, then use the command line to cd into it, and then execute npm init , a long list of forms will be generated, fill in the content according to your actual situation

name: fill in the name of your package, the default is the name of your folder. But I want to emphasize here that it is best to go to npm to find out if there is a package with the same name. The best way to test is to enter npm install on the command line with the name you want. If an error is reported, then good. There is no package with the same name as yours on npm. You can publish the package with confidence. If downloaded successfully. . . So unfortunately, change the name. . .

version: The version of your package, the default is 1.0.0

description: Actually, I don’t know what it is, press Enter Enough. . . , use one sentence to describe what your package is used for

entry point: Entry file, the default is Index.js, you can also fill it in yourself Your own file name

test command:Test command, just press Enter for this, because this is not needed yet.

git repository: This is the git warehouse address. If your package is first placed on github or other git warehouse, then there will be a hidden one in your folder. git directory, npm will read this directory as the default value for this item. If not, just press Enter to continue.

keyword: This is an important point, it is related to how many people will search for your npm package. Try to use appropriate keywords as the index for this package. My package first works under express, then it is a plug-in, and then it is a registered route for route, and this route is based on the file directory dir, so I can easily figure out my package. index key.

author: Write your account or your github account

license: Just press enter here, the open source file is here. . .

Then it will ask you Are you ok?

Press Enter Ok!

Then we go back to our file directory and take a look, and find that there is an extra package.json file

Then, create a new index.js file in the directory, or you just modified it If the value of that entry point is determined, then your file name will also be changed to that value.

My npm projectDirectory structure is like this. Note that the bin folder is generated by me to make a command line tool, which will be discussed later. Talking about how to generate command line tools; of course, if you don’t want to generate command line tools, this folder is not needed.

Because I threw all the encapsulated code in the lib, there is only one sentence in index.js:

module.exports=require('./lib')

Then, the most important thing is to write README.md, a Give everyone a markdown file describing your package. If no one knows what your code does, will anyone download your code? Oh, by the way, it’s best to write in English.

2. npm publish

After writing your own npm package, you can publish it to npm after the test runs without problems

First you must register an npm account

Use the npm command to log in

Then, use npm publish in your directory

##Note:Under normal circumstances, once you want to modify the code you have published, and then perform the publishing operation, be sure to go to package.json and change the version, such as changing it from 1.0.0 to 1.0.1. Then execute npm publish, so that it can be published successfully.

3. Generate command line tools

在使用 Nodejs 过程中,有很多包都支持全局安装,提供一个命令,然后在命令行我们就可以完成一些任务。有时候我们也需要开发这样的命令工具。在Node.js 中发现弄个命令行工具特别轻松。我使用的是commander包来生成命令行工具

$ npm install commander

然后cd到bin目录下,新建一个.js文件(名字自取),编写代码,在js文件顶部加上#!/usr/bin/env node

例如我的geAsar.js:

#!/usr/bin/env node
var asar = require('../lib/geAsar')
var program = require('commander');
program.version('v' + require('../package.json').version)
  .description('Manipulate asar archive files')
program.command('pack <dir> <output>')
  .alias('p')
  .description('create asar archive')
  .action(function (dirpath, output) {
   asar.geAsar(dirpath,output);
   console.log(output+"文件成功生成");
  })
program.parse(process.argv)
if (program.args.length === 0) {
 program.help()
}</output>
</dir>

然后还需在package.json中添加

"bin": { 
 "geAsar": "./bin/geAsar.js" 
 },

运行 node bin/geAsar.js 会显示当前文件夹下的所以文件和文件夹名。这个玩意儿真的跑起来了.

全局运行命令调试

install

如果在项目目录下运行没有问题,可以将当前目录模块安装到全局,也可以采用此方法来更新你的命令行工具

sudo npm install . -g

link

或者目录输入 npm link 会自动添加全局的 symbolic link ,然后就可以使用自己的命令了。 (我用的是这个)

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样使用angularjs中http服务器

vue中keep-alive使用方法详解

vue项目中type=”file“ change事件只执行一次怎样处理

The above is the detailed content of How to use Nodejs to publish npm packages and make them into command line tools. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),