nodejs

Node.js 事实上就是一种上下文,它允许在后端(脱离浏览器环境)运行 JavaScript 代码。 要实现在后台运行 JavaScript 代码,代码需要先被解释然后正确的执行。 Node.js 使用 Google 的 V8 虚拟机来解释和执行 JavaScript 代码。 除此之外,Node.js 的还有许多有用的模块,可以简化很多重复的劳作,比如向终端输出字符串。 因此,Node.js 事实上既是一个运行时环境,同时又是一个库。

NPM Nodejs Package Manager 默认的包管理工具

npm install 模块名 [-g]
安装模块
--save-dev 依赖信息保存到 package.json 的 devDependencies 中。
--save 依赖信息保存到 package.json 的 dependencies 中。
npm uninstall 模块名 [-g]
卸载本地[全局]模块
npm list [-g]
查看已安装的本地[全局]模块
npm update 模块名 [-g]
更新本地[全局]模块
npm search 模块名
搜索模块
npm publish
发布本地模块的NPM库
npm unpublish 模块名@版本号
撤销指定版本的模块发布
npm config get config_name
读取配置
npm config set config_name
设置配置
npm config set registry https://registry.nom.taobao.org
npm config delete config_name
删除配置
npm config delete registry
npm run 命令
执行 package.json 中 scripts 定义的命令

版本号说明

版本号格式 X.Y.Z,本别代表主版本号、次版本号和补丁版本号。

当代码有修改时,需按以下规则执行版本号变更:

版本号限定符含义

^0.1.0 = [0.1.0, 1.0.0) ~0.1.0 = [0.1.0, 0.2.0) 0.1.0 = 0.1.0 >=0.1.0 = [0.1.0, 无穷大) * = 任意版本

异步编程风格

回调函数的第一个参数永远是Error对象 func(param..., callback(Error, data)) Promise(function(resolve, reject): Promise{ //异步逻辑 }) Promise的状态 pending; fulfilled; reject Promise.prototype.then = function(onFulfilled[, onRejected]): Promise onFulfilled Promise 执行成功时回调 onRejected Promise 执行出错时回调,该参数是可选的 then方法: 返回一个新的 Promise 对象,因此 Promise 支持链式调用 Promise.prototype.catch = function(onRejected): Promise

常用核心模块

event 基本使用步骤 实例化事件监听器实例,注册事件,触发事件 fs 读readFile() 写writeFile() 增appendFile(path, content) 删unlink(path) stream 读取流 readStream = fs.createReadStream('path.name', {encoding:'utf-8'}) 写入流 writeStream = fs.createWriteStream() 管道流 readStream.pipe(writeStream) 数据转换流 http

grunt入门

官方入门教程
  1. npm install -g grunt-cli
    注意,安装grunt-cli并不等于安装了 Grunt! Grunt CLI的任务很简单:调用与Gruntfile在同一目录中 Grunt。 这样带来的好处是,允许你在同一个系统上同时安装多个版本的 Grunt。
  2. 配置好package.jsonGruntfile后:
    1. 将命令行的当前目录转到项目的根目录下。
    2. 执行npm install命令安装项目依赖的库。
    3. 执行 grunt 命令。

Nodejs 察看当前配置信息 2024.3.7日

where npm D:\greenSoft\nodejs\npm D:\greenSoft\nodejs\npm.cmd D:\greenSoft\nodejs\node_global\npm D:\greenSoft\nodejs\node_global\npm.cmd

npm root -g # Print the effective node_modules folder to standard out. D:\greenSoft\nodejs\node_global\node_modules

node -v v20.9.0 npm -v 10.2.3

npm config get cache D:\greenSoft\nodejs\node_cache C:\Users\admin>npm config get prefix D:\greenSoft\nodejs\node_global

npm list -g D:\greenSoft\nodejs\node_global +-- cnpm@9.2.0 +-- electron@27.0.3 +-- http-server@14.1.1 +-- npm@10.2.3 `-- yarn@1.22.19

设置方法: npm config set prefix "D:\greenSoft\nodejs\node_global" 也可在文件 node_modules\npm\.npmrc 中添加 prefix=D:\greenSoft\nodejs\node_global