前端进阶之旅前端进阶之旅
基础篇
进阶篇
高频篇
精选篇
手写篇
原理篇
面经篇
自检篇
每日一题
  • 综合
    • 综合题型
    • 其他问题
    • 设计模式
    • 思维导图
    • 学习路线
  • 前端基础
    • HTTP
    • 浏览器
    • 计算机基础
  • 进阶学习
    • NPM工作流
    • Docker
    • Canvas
    • Node学习指南
    • 前端综合文章
  • 其他
    • Handbook
    • 职场话题
    • CSS可视化
小程序题库
公众号动态
博客动态
开发者导航
基础篇
进阶篇
高频篇
精选篇
手写篇
原理篇
面经篇
自检篇
每日一题
  • 综合
    • 综合题型
    • 其他问题
    • 设计模式
    • 思维导图
    • 学习路线
  • 前端基础
    • HTTP
    • 浏览器
    • 计算机基础
  • 进阶学习
    • NPM工作流
    • Docker
    • Canvas
    • Node学习指南
    • 前端综合文章
  • 其他
    • Handbook
    • 职场话题
    • CSS可视化
小程序题库
公众号动态
博客动态
开发者导航

一次node文件操作过多排查过程总结

首页
2022-02-16 15:55:24
Front-End
Node

最近在优化公司内部的脚手架,遇到一个问题,Error: EMFILE, too many open files也就是nodejs打开文件过多会导致错误,一次次排查,最后找到了一个有效的方法,总结记录一下

当我尝试去操作大量文件的时候

for(var i=0; i<200000; i++) {
    fq.readFile('./somefile.txt', {encoding: 'utf8'}, function(err, somefile) {
        console.log("data from somefile.txt without crashing!", somefile);
    });
}
@前端进阶之旅: 代码已经复制到剪贴板

以上导致Error: EMFILE: too many open files错误。我不必关闭文件,因为显然可以fs.readFile对文件进行操作并为我关闭文件。我在Mac OS上,我的ulimit设置为8192

$ ulimit -a
-t: cpu time (seconds)              unlimited
-f: file size (blocks)              unlimited
-d: data seg size (kbytes)          unlimited
-s: stack size (kbytes)             8192
-c: core file size (blocks)         0
-v: address space (kbytes)          unlimited
-l: locked-in-memory size (kbytes)  unlimited
-u: processes                       1392
-n: file descriptors                256
@前端进阶之旅: 代码已经复制到剪贴板

可以通过修改系统配置,但是不太推荐

$ echo kern.maxfiles=65536 | sudo tee -a /etc/sysctl.conf
$ echo kern.maxfilesperproc=65536 | sudo tee -a /etc/sysctl.conf
$ sudo sysctl -w kern.maxfiles=65536
$ sudo sysctl -w kern.maxfilesperproc=65536
$ ulimit -n 65536 
@前端进阶之旅: 代码已经复制到剪贴板
  • 由于node.js的异步特性,因此会发生此错误。进程试图打开的文件超出允许的数量,因此会产生错误。
  • 可以通过创建打开文件队列来解决此问题,以使它们永远不会超过限制,以下是一些可以为您完成此操作的库:

我们可以使用文件队列来限制每次打开的文件数量

Instantiate Filequeue with a maximum number of files to be opened at once (default is 200)

how to use

var FileQueue = require('filequeue');
var fq = new FileQueue(100);

// additional instances will attempt to use the same instance (and therefore the same maxfiles)

var FileQueue2 = require('filequeue');
var fq2 = new FileQueue2(100);

console
fe

← Nestjs学习总结教你如何使用vercel服务免费部署前端项目和serverless api →