Node.js使用中常见的问题解答
1、想替换 redis 的值,需要先删除后再设置,否则不会覆盖;并且 ttl 必须是整数,不能有小数点,否则报错
2、nodejs 在 windows 下的路径和 mac 下的路径解析,可以使用 path.join 进行连接;
3、针对单个项目使用 npm 配置,在项目根目录创建 .npmrc 文件重写部分配置即可,其他的项目不受影响
registry=https://registry.npmmirror.com
4、npm install 报错,提示包下载失败
git config --global url."https://".insteadOf git://
5、npm install 多个包的版本
查看:https://docs.npmjs.com/cli/v9/commands/npm-install
npm install <alias>@npm:<name>
使用别名安装软件包,允许多个版本的同名包同时安装,为具有较长的包更方便导入名称,别名仅适用于项目,不会重命名传递依赖项中的包。npm install my-react@npm :react npm install jquery2@npm : jquery@2 npm install jquery3@npm : jquery@3 npm install antd4@npm : antd@4.19.5
6、启动一个随机的端口号的服务器
var server = http.createServer();
server.listen(0);
server.on('listening', function() {
var port = server.address().port
});
// 监听 0 端口,nodejs会自动分配给你一个可用端口,listening中获取port就ok了。。就这么简单。
7、axios 的 https 证书过期了解决方案
https 证书过期之后,axios 请求的时候会报错,nodejs 程序可以使用下面的方式跳过 https 证书的校验;
const axios = require('axios');
const https = require('https');
axios.defaults.httpsAgent = new https.Agent({
rejectUnauthorized: false
});
重新调用之后就没有问题了;
8、删除 require 的模块的缓存 #nodejs模块缓存 防止多次调用,内存爆炸
nodejs 删除缓存的模块,查看 require使用说明。
const tempFile = "./temp.js";
const tempFn = require(tempFile);
// 删除缓存
require.cache[require.resolve(tempFile)] = undefined;
// delete require.cache[require.resolve(tempFile)]
// tempFn 注意删除了缓存,在这里执行还是可以的,下次引入文件的时候会自动加载
tempFn();
Modules: CommonJS modules | Node.js v20.2.0 Documentation
require.cache 存储了已经 require 过的模块,可以通过删除缓存的 key 来让 nodejs 下次加载的时候重新加载该模块(这个方法会 native 模块不生效),如果模块修改了,那重新加载会得到修改后的模块的内容,适合热加载模块的场景。
Modules are cached in this object when they are required. By deleting a key value from this object, the next
require
will reload the module. This does not apply to native addons, for which reloading will result in an error.
9、在业务代码中使用的依赖一定要放到 dependence 中,否则设置 NODE_ENV=production 后,执行 npm install 不会安装会报错