nodejs 常见异常

nodejs 常见问题

一、nodejs 版本升级

  • 原始环境
    OS: win10系统,64位
    node: 10.15.*
  • 升级到最新环境
    查阅资料显示使用如下命令
# 执行如下语句
npm i -g n
# 报错如下
npm ERR! code EBADPLATFORM
npm ERR! notsup Unsupported platform for n@7.0.0: wanted {"os":"!win32","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm ERR! notsup Valid OS:    !win32
npm ERR! notsup Valid Arch:  any
npm ERR! notsup Actual OS:   win32
npm ERR! notsup Actual Arch: x64

在这里插入图片描述
意思很明显:需要非**!win32**环境,那就是咱们window没有这波红利,看样子只能官网下载覆盖更新咯;
nodejs 官方地址:https://nodejs.org/zh-cn/download/
在这里插入图片描述
下载 --> 安装(一路点next就搞定了)
参考博客

https://blog.csdn.net/guzhao593/article/details/81712016

二、Cannot use import statement outside a module

环境介绍

  1. os: win10
  2. IDE: VSCODE
  3. node: v14.15.4
  4. bable: 6.26.0

异常

PS D:\code\vscode\edu\nodejs_demo\babel_demo> node .\es6\002.js
(node:27252) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
D:\code\vscode\edu\nodejs_demo\babel_demo\es6\002.js:1
import {getList ,save} from "./001"
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47
PS D:\code\vscode\edu\nodejs_demo\babel_demo>

在这里插入图片描述

babel作用:将部分浏览器支持的ES6语法转换成市场上全部浏览器支持的ES5语法

查阅资料:nodejs不支持import语法,如果要支持,需要babel来支持,而我本身是安装过bable的,为了尽快解决错误,决定安装支持ES6语法的bable-node

异常解决

  1. npm全局安装pm2
npm install -g pm2
  1. 安装babel相关模块
npm install --save babel-core
npm install --save babel-preset-es2015
# es2015与env 二选一即可
# npm install --save babel-preset-env
npm install babel-cli -g
  1. 创建.babelrc文件
# 若es2015,文件内容固定如下
{
    "presets": [
     "es2015"
    ],
    "plugins": []
}
# 若env,文件内容固定如下
{
    "presets": [
     "env"
    ],
    "plugins": []
}

在这里插入图片描述

测试使用

方式一 使用babel 将es6语法转换成es5语法
  1. 生成es5文件
babel ./es6/ -d ./es05/

在这里插入图片描述
查看es文件
./es6/001.js

export function getList(){
    console.log("getList......")
}

export function save(){
    console.log("save.........")
}

./es6/002.js

import {getList ,save} from "./001"

getList()
save()

./es5/001.js

"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.getList = getList;
exports.save = save;
function getList() {
    console.log("getList......");
}

function save() {
    console.log("save.........");
}

./es5/002.js

"use strict";

var _ = require("./001");

(0, _.getList)();
(0, _.save)();
  1. 使用babel运行js脚本
node ./es5/002.js

在这里插入图片描述

方式二 使用babel 将es6语法转换成es5语法
babel-node ./es6/002.js

在这里插入图片描述
参考网址

运行nodejs项目,npm start启动项目import报错 https://blog.csdn.net/ll837448792/article/details/103307796
nodejs之使用babel支持es6和pm2下使用babel https://blog.csdn.net/wushichao0325/article/details/85262063

三、babel-node : 无法加载文件 C:\Users***\AppData\Roaming\npm\babel-node.ps1

babel-node : 无法加载文件 C:\Users\***\AppData\Roaming\npm\babel-node.ps1,因为在此  
系统上禁止运行脚本。有关详细信息,请参阅 https:/go.microsoft.com/fwlink/?LinkID=135170  
中的 about_Execution_Policies。
所在位置 行:1 字符: 1
+ babel-node .\demo1.js
+ ~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [],PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

在这里插入图片描述
执行如下命令

set-ExecutionPolicy RemoteSigned

在这里插入图片描述
参考网址

https://blog.csdn.net/zhizhengguan/article/details/103291251

四、国内npm镜像

问题

开发者为了加速下载依赖package,一般使用 https://registry.npm.taobao.org 作为仓库 ,有时候仓库没有及时更新,会找不到对应的package

npm ERR! 500 Internal Server Error - GET https://registry.npm.taobao.org

解决方案

我们可以换一个仓库镜像
国内可用官方镜像:

  • npm官方地址:https://www.npmjs.com/ (全)
  • npm官方镜像:https://registry.npmjs.org/ (全)

国内优秀npm镜像
淘宝npm镜像 (快)

  • 搜索地址:http://npm.taobao.org/
  • registry地址:http://registry.npm.taobao.org/

cnpmjs镜像

  • 搜索地址:http://cnpmjs.org/
  • registry地址:http://r.cnpmjs.org/
  1. 临时使用
npm install express --registry https://registry.npm.taobao.org 

2.持久使用

# 查看持久配置
npm config get registry 
## 设置持久配置
npm config set registry https://registry.npm.taobao.org
  1. 通过cnpm使用
## 安装
npm install -g cnpm --registry=https://registry.npm.taobao.org
# 使用
cnpm install express
Node.js捕获异常的方式有多种。首先,可以使用try...catch语句块来捕获同步代码中的异常。这意味着在可能抛出异常的代码块之前使用try关键字,并在可能抛出异常的代码块之后使用catch关键字来处理异常。 另一种捕获异常的方式是通过处理异步回调函数中的异常。在Node.js中,大多数异步操作都是通过回调函数来处理的,当发生异常时,回调函数将接收到错误对象作为参数。可以在回调函数中使用try...catch语句块来捕获并处理异常。 除了使用try...catch语句块来捕获异常外,还可以使用事件和Promise来处理异常Node.js提供了一些内置的事件,如'uncaughtException',可以用来捕获未被捕获的异常。此外,使用Promise可以更灵活地处理异步操作中的异常。 下面是一个示例代码,演示了如何在Node.js中捕获异常: ```javascript const cluster = require('cluster'); const os = require('os'); const http = require('http'); const domain = require('domain'); const d = domain.create(); if (cluster.isMaster) { const cpuNum = os.cpus().length; for (let i = 0; i < cpuNum; i++) { cluster.fork(); } cluster.on('fork', worker => { console.info(`${new Date()} worker ${worker.process.pid} 进程启动成功`); }); cluster.on('exit', (worker, code, signal) => { console.info(`${new Date()} worker ${worker.process.pid} 进程启动异常退出`); cluster.fork(); }); } else { http.createServer((req, res) => { d.add(res); d.on('error', (err) => { console.log('记录的err信息', err.message); console.log('出错的 work id:', process.pid); res.end('服务器异常,请稍后再试'); cluster.worker.kill(process.pid); }); d.run(handle.bind(null, req, res)); }).listen(8080); } function handle(req, res) { if (process.pid % 2 === 0) { throw new Error(`出错了`); } res.end(`response by worker: ${process.pid}`); }; ``` 在上面的示例代码中,我们使用了domain模块来捕获异常,并使用try...catch语句块来捕获同步代码中的异常。当发生异常时,我们记录了错误信息,并向客户端发送了一个错误的响应。如果是主进程发生异常,我们会重新fork一个子进程来替代。 <span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值