nodejs使用技巧和常见问题汇总

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时。
官网:http://nodejs.cn/
API: 查看文档

包管理 NPM

1.英文缩写(node package manager),是 JavaScript 世界的包管理工具,并且是 Node.js 平台的默认包管理工具。安装完nodejs就可以使用 全局环境变量npm。

2.如何使用:

//查看npm版本
npm -v 
//查看npm所有使用信息 
npm -l 
//查看全局安装软件的根目录
npm root -g
//查看软件包 历史版本
npm view XX versions
//安装软件包
npm i XX -g  
//安装到指定版本
npm install gulp@1.1.1 
//安装package.json依赖包
npm install
npm install --dependencies
npm install --devDependencies
//清理缓存
npm cache clean --force

//查看tsc是运行在那个目录
where.exe tsc 

3.npm,npx和yarn的区别:

yarn: 是经过重新设计的npm 客户端;运行速度显著提升,整个安装时间比 npm 少。
yarn提供了离线模式,无需互联网连接就能安装本地缓存的依赖项。

npx: 先检查当前项目node_modules/下,是否存在。不存在的话,就检查全局是否已经安装对应的模块。如果还没有的话,就去仓库里面去下载对应的模块,下载完毕就执行。执行完毕就删除,不留下一丝痕迹

//设置淘宝源 npm安装插件是从国外服务器下载,受网络影响大,可能出现异常。淘宝团队复制了一个完成的镜像,同步频率目前为10分钟一次。
npm config set registry https://registry.npm.taobao.org/
//安装yarn
npm i yarn -g
//初始yarn
yarn install   |   yarn add electron

4.全局切换node版本
有时项目有低版本和高版本,配套的node也需要多样的版本,可以使用nvm进行切换,下载
安装之前,输入npm cache clean --force 回车执行,把之前安装的清除一下。

nvm -v                //查看nvm版本
nvm list              //查看nvm已经安装的node版本
nvm list available    //查看nvm能够安装的node版本列表
nvm install node版本  //安装指定的node版本
nvm uninstall node版本   //卸载指定node版本
nvm use 20.0.0 //切换版本号

基础用法

1.参数传递

//传入
node test.js arg1 arg2

//获取node
let node = process.argv.splice(0);
//获取执行的js的完整路径
let js_name = process.argv.splice(1);	
//参数数组
let arguments = process.argv.splice(2);		
arg1 = arguments[0];
arg2 = arguments[1];
//注意这样取值,会出现错误 
process.argv.splice(2)[0]  有值
process.argv.splice(2)[1]  无值

2.删除文件夹

/**
 * 删除文件
 * @param url 
 * @param isDelFolder 是否删除文件夹
 */
function deleteFiles(url, isDelFolder=false) {
    let files = [];
    //判断给定的路径是否存在
    if (fs.existsSync(url)) {
        //返回文件和子目录数组
        files = fs.readdirSync(url);
        files.forEach(function (file, index) {
            const curPath = path.join(url, file);			
            //console.log(curPath);
            //文件夹递归调用
            if (fs.statSync(curPath).isDirectory()) {
                deleteFiles(curPath,isDelFolder);
            } else {
                fs.unlinkSync(curPath);
            }
        });
        //清除文件夹
        isDelFolder&& fs.rmdirSync(url);
    } else {
        console.log("文件路径不存在,请给出正确的路径");
    }
}

3.创建文件夹

//可创建空目录
fs.mkdirSync(destination, { recursive: true });

4.复制 复制文件详情 复制文件夹详情

//复制文件
fs.copyFileSync(src, dest);
//复制文件夹 需v16.7.0  
//@param preserveTimestamps 是否保留原时间戳
//param filter 过滤复制文件/目录的函数
var filter
fs.cpSync(src, dest,{recursive:true,force:true,preserveTimestamps:true,filter:Function})

常用工具包

1.WebPack
模块打包器,主要目的是在浏览器上打包 JavaScript 文件。 可以根据 ES 、CommonJS 或 AMD 模块依赖关系将js,css文件合并。

2.uglifyjs
压缩说明 混淆原理
功能:遍历AST语法树,做各种操作,比如自动缩进、缩短变量名、删除块括号{}、去空格、常量表达式、连续变量声明、语块合并、去掉无法访问的代码等。
安装:uglify-js 支持es5 ; uglify-es 支持es6
使用:uglifyjs code.js -o -m code.min.js

问题:打包出现:Unexpected token: keyword «const»
解决:里边出现了es6语法,比如const常量,安装uglify-es,或者将代码转化为es5。

3.gulp
问题:Local gulp not found in
解决:npm link gulp,把全局gulp链接到本地项目

问题:task function must be specified 或primordials is not defined
解决:必须指定任务函数,安装了gulp4.0.0,gulpfile.js用的是gulp3.9.1的语法。gulp还原到3.9.1即可

4.生成.d.ts文件

npm install -g npm-dts
cd /your/project
npm-dts generate

出现问题:使用npm-dts命令时提示无法加载文件 C:\Users\xx\AppData\Roaming\npm\npm-dts.ps1
解决方法:右键开始菜单找到Windos PowerShell(管理员),执行set-ExecutionPolicy RemoteSigned命令,输入A即可。

5.eslint
代码风格检测
问题:✖ 1784 problems (1784 errors, 0 warnings) 1784 errors and 0 warnings potentially fixable with the --fix option.
解决:npm run lint --fix,执行后,使用npm运行lint命令时,自动修复代码中的错误和警告

常见问题:

1.问题: 无法加载文件 AppData\Roaming\npm\gulp.ps1解决方法,因为在此系统上禁止运行脚本。
解决:在cmd输入:Get-ExecutionPolicy -List ,Set-ExecutionPolicy RemoteSigned -Scope Process

2.问题:使用空值合并操作符?? 出现 ‘SyntaxError: Unexpected token ?’
解决:这些新的语法是在 ECMAScript 2020 引入的,使用node -v查看你的node版本,低于14需要升级。

3.问题:If you want to include a polyfill, you need to:add a fallback ‘resolve.fallback: { “stream”: require.resolve(“stream-browserify”) }’

ERROR in ./node_modules/cipher-base/index.js 2:16-43
  Module not found: Error: Can't resolve 'stream' in 'D:\nodejs\demo2\node_modules\cipher-base'

  BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
  This is no longer the case. Verify if you need this module and configure a polyfill for it.

  If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
        - install 'stream-browserify'
  If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "stream": false }
  resolve 'stream' in 'D:\nodejs\demo2\node_modules\cipher-base'

解决:webpack5和webpack4有差异,webpack5需要额外处理:安装 npm i stream-browserify
在package.json,增加以下配置:

"dependencies": {
    "axios": "^1.6.8",
    "electron-forge": "^5.2.4",
    "electron-squirrel-startup": "^1.0.0",
    "crypto": "^1.0.1",
    "crypto-browserify": "^3.12.0",
    "stream-browserify": "^3.0.0",
    "webpack-node-externals": "^3.0.0"
  },
 "browser": {
 //增加这个,是遇到stream时,会使用后面stream-browserify这个模块
 	"crypto": "crypto-browserify",
    "stream": "stream-browserify"
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值