2

Our system has (evidently) too many open files:

Error: EMFILE: too many open files

Should we explicitly close files after:

import * as fs from 'fs';
for (const filename in filenames) {
  const text = fs.readFileSync(filename).toString();
  // explictly close the file? how?
}

It seems that canonical answers (like this one) don't mention it.

OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87

1 Answers1

1

Here is a solution that wraps the readFileSync with openSync and closeSync:

import { openSync, closeSync, readFileSync, writeFileSync } from 'fs'

const d1 = openSync('input.json', 'r')
const data = readFileSync(d1).toString();
closeSync(d1)

const parsedData = JSON.parse(data)
const filenames = new Array<string>();

for (const n of parsedData) {
  filenames.push(n['name']);
}

let mydata = [];
for (const filename of filenames) {
  const d = openSync(filename, 'r')
  mydata.push(readFileSync(d).toString())
  closeSync(d)
}

console.log(mydata.length)

It opens + reads + closes 100,000 files in a loops without any problem:

$ grep -rn "\"name\": " input.json | wc -l
100001
$ npx tsc main.ts                         
$ node ./main.js                          
100001
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87