nodeHow to write files into npm packages? The following article will introduce to you how to copy the node file into an npm package and publish it. I hope it will be helpful to you!
Copy the node file into an npm package and publish it
npm plug-in release
Publishing npm is actually It's a very simple thing. I just forgot about it because I haven't released it for a long time, and I have to look it up online, so I wrote an article to record it. [Recommended learning: "nodejs Tutorial"]
Create a new file directory
- Create a new directory and name it Any
- Run the command to generate
package.json
npm init --yes
Install dependencies
if The project also requires other dependencies, which can be installed through npm install xxx
as during normal development.
However, one thing to note here is the difference between -S
, --save
and --save-dev
, because this is usually done when developing projects. There is no essential difference between the three, but there is still a difference when developing npm package
- ##-S
and
--saveThe downloaded plug-in will be written to
dependencies, and when we install the custom plug-in, it will be downloaded together
- --save-dev
The plug-in will be written to
devDendencies. This is only used during development and will not be installed along with the custom plug-in.
Completepackage.json<span style="font-size: 16px;"></span>
- name
Others need to install this plug-in through
npm install xxx, to install this
xxxcorresponds to the
value# of
name
##version - The version of the plug-in, you need to re-release this version every time, otherwise the release will fail
- Entry file
{ "name": "node-fs-copy", //发布的包名,默认是上级文件夹名。不得与现在npm中的包名重复。包名不能有大写字母/空格/下滑线! "version": "1.0.0",//你这个包的版本,默认是1.0.0。对于npm包的版本号有着一系列的规则,模块的版本号采用X.Y.Z的格式,具体体现为: 1、修复bug,小改动,增加z。 2、增加新特性,可向后兼容,增加y 3、有很大的改动,无法向下兼容,增加x "description": "", "main": "index.js",//入口文件,默认是Index.js,可以修改成自己的文件,这个很重要,当你在实际项目使用的时候,let a = require("包名"),它就去会去找对应的文件路径哦。 "scripts": { // 快捷命令,在package.json同目录下输入命令 npm run 键 就会执行 相对应的命令 "bulid": "npx webpack --config myConfig.js" //例如 输入 npm run bulid 就会执行npx webpack --config myConfig.js的命令 。 }, "keywords": [ // npm搜索的关键字 "node", "fs", "copy" ], "publishConfig": { "registry": "" // 发布的npm地址 }, "repository": { "type": "git", "url": "git+https://github.com/xxxx" // 代码的git地址 }, "author": "zxw", "license": "ISC",//这个直接回车,开源文件协议吧,也可以是MIT,看需要吧。 "dependencies": { // 生产环境所依赖的包 "jquery": "^3.4.1", "sea": "^1.0.2" }, "devDependencies": { // 开发环境所依赖的包 "webpack": "^4.41.6" } }
After confirming that the entry file is index.js, and writing the code, note that both introduction and export need to be done through node
index.jsconst { exists, copyDir} = require('./lib/copy') const fsCopy = (sourcePath, deptPath)=> { exists(sourcePath,deptPath, copyDir) } module.exports = { fsCopy }
const fs = require('fs') /** * 复制一个文件夹下的文件到另一个文件夹 * @param src 源文件夹,即需要写出的文件 * @param dst 目标文件夹,需要写入的文件 */ const copyDir = function (src, dst) { // 读取目录中的所有文件/目录 fs.readdir(src, function (err, paths) { if (err) { throw err } paths.forEach(function (path) { const _src = src + '/' + path const _dst = dst + '/' + path let readable; let writable fs.stat(_src, function (err, st) { if (err) { throw err } // 判断是否为文件 if (st.isFile()) { // 创建读取流 readable = fs.createReadStream(_src) // 创建写入流 writable = fs.createWriteStream(_dst) // 通过管道来传输流 readable.pipe(writable) } // 如果是目录则递归调用自身 else if (st.isDirectory()) { exists(_src, _dst, copyDir) } }) }) }) } /* * 判断当前目标文件是否存在 * 如若不存在需要先进行创建 * */ const exists = function (src, dst, callback) { // 如果路径存在,则返回 true,否则返回 false。 if (fs.existsSync(dst)) { callback(src, dst) } else { fs.mkdir(dst, function () { callback(src, dst) }) } } module.exports = { exists, copyDir }
TestThis piece I just conducted a relatively simple test, and I will add a dedicated chapter on plug-in testing later
Publish
Register npm account, usually npm can log in directly by associating with gitlab- Make sure your current image points to the npm image instead of the Taobao image. If you are not sure, you can directly execute
npm config set registry https://registry.npmjs.org/
npm addUser
npm publish
As shown in the picture, the release is successful.
Publish errorIf the release encounters a
403 error, it is very It is possible that the name
field in your package name, i.e. package.json
, is the same as the existing plugin name in npm
. You need to modify it and re-publish itAfter modifying the name, an error still occurs,
, indicating that this version already exists in npm
, and the version number needs to be modified
IterationIf there are any changes in the subsequent content, you need to manually change it every time you re-publish it
package.json/version version number, and then execute the published command
installnpm install node-fs-copy
In node code, local copy testconst { fsCopy } = require('node-fs-copy')
// 把内容从本地D盘的test/test目录,拷贝到test/test1目录
fsCopy('d:/test/test', 'd:/test/test1')
Server code copyLocal is There is no way to directly copy the server code. If you need to copy the server code, you need to meet a condition
The node server code and the file to be copied are on the same server- For example, the file address on the author's server is
, and the node service is also deployed in another directory on the same server <pre class='brush:php;toolbar:false;'>//在服务器上运行,表示把服务器的/data/code-generator文件内的内容,拷贝到当前项目的./temporary/test内
fsCopy(&#39;/data/code-generator&#39;, &#39;./temporary/test&#39;)</pre>
After completing the copy, you can use the packaging plug-in Compress the content into
, output it to the front end, then delete the temporary file ./temporary/test
, and then delete the zip package
<h2 id="strong-附上常用命令-strong"><strong>附上常用命令</strong></h2><pre class='brush:php;toolbar:false;'>npm init --yes(初始化配置)
npm i (会根据package.json里面的键dependencies,devDependencies来安装相对应的包)
npm i 包(默认安装一个最新的包,这个包在node_modules文件夹里面,并且会更新在你的package.json文件)
npm i 包@3.0.0(安装一个指定版本的包,会更新在你的package.json文件)
npm i 包 --save-dev(安装一个开发环境所需要的包,会更新在你的package.json文件)
npm uninstall 包(卸载一个包,会更新在你的package.json文件)
npm update 包(更新此包版本为最新版本,会更新在你的package.json文件)
npm run 脚本键(会根据package.json里面的"scripts"里面的脚本键自动执行相对于的值)
npm publish (根据package.json的name发布一个包)
npm unpublish 包名 --force(卸载npm网站上自己上传的包)</pre><p>更多编程相关知识,请访问:<a href="https://www.php.cn/course.html" target="_blank" textvalue="编程视频">编程视频</a>!!<br></p>
The above is the detailed content of How to write node files into npm packages and publish them?. For more information, please follow other related articles on the PHP Chinese website!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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),

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment