几天来,我一直在寻找一个有效的错误解决方案

错误:EMFILE,打开的文件太多

似乎很多人都有同样的问题。通常的答案是增加文件描述符的数量。所以,我试过了:

sysctl -w kern.maxfiles=20480

缺省值为10240。在我看来,这有点奇怪,因为我在目录中处理的文件数量低于10240。更奇怪的是,在增加了文件描述符的数量之后,我仍然收到相同的错误。

第二个问题:

经过多次搜索,我找到了一个解决“打开文件太多”问题的方法:

var requestBatches = {};
function batchingReadFile(filename, callback) {
  // First check to see if there is already a batch
  if (requestBatches.hasOwnProperty(filename)) {
    requestBatches[filename].push(callback);
    return;
  }

  // Otherwise start a new one and make a real request
  var batch = requestBatches[filename] = [callback];
  FS.readFile(filename, onRealRead);
  
  // Flush out the batch on complete
  function onRealRead() {
    delete requestBatches[filename];
    for (var i = 0, l = batch.length; i < l; i++) {
      batch[i].apply(null, arguments);
    }
  }
}

function printFile(file){
    console.log(file);
}

dir = "/Users/xaver/Downloads/xaver/xxx/xxx/"

var files = fs.readdirSync(dir);

for (i in files){
    filename = dir + files[i];
    console.log(filename);
    batchingReadFile(filename, printFile);

不幸的是,我仍然收到相同的错误。 这段代码有什么问题?


当前回答

这可能发生在更改Node版本之后 ERR emfile太多打开的文件

重新启动计算机 酿造安装看守

它应该完全解决这个问题

其他回答

吹风笛,你只需要零钱

FS.readFile(filename, onRealRead);

=>

var bagpipe = new Bagpipe(10);

bagpipe.push(FS.readFile, filename, onRealRead))

风笛帮助你限制平行动作。详情:https://github.com/JacksonTian/bagpipe

请注意,您不必将这个问题过于复杂化,再试一次就可以了。

import { promises as fs } from "fs";

const filepaths = [];
const errors = [];

function process_file(content: string) {
    // logic here
}

await Promise.all(
    filepaths.map(function read_each(filepath) {
        return fs
            .readFile(filepath, "utf8")
            .then(process_file)
            .catch(function (error) {
                if (error.code === "EMFILE") return read_each(filepath);
                else errors.push({ file: filepath, error });
            });
    }),
);

首先使用expo update更新你的expo版本,然后运行yarn / NPM install。这为我解决了问题!

在Windows上,似乎没有ulimit命令来增加打开文件的数量。在graceful-fs中,它维护一个队列来运行I/O操作,例如:读/写文件。

然而,fs。readFile, fs。writeFile是基于fs的。打开,因此您需要手动打开/关闭文件来解决此错误。

import fs from 'fs/promises';

const fd = await fs.open('path-to-file', 'r');

await fd.readFile('utf-8'); // <== read through file handle
await fd.close();           // <== manually close it

以@blak3r的回答为基础,以下是我使用的一些速记,以防它有助于其他诊断:

如果你试图调试一个正在耗尽文件描述符的node .js脚本,这里有一行给你问题节点进程使用的lsof的输出:

openFiles = child_process.execSync(`lsof -p ${process.pid}`);

这将同步运行由当前运行的Node.js进程过滤的lsof,并通过缓冲区返回结果。

然后使用console.log(openFiles.toString())将缓冲区转换为字符串并记录结果。