在 readFileSync 之后显式关闭文件

explicitly closing a file after readFileSync

提问人:OrenIshShalom 提问时间:3/21/2023 更新时间:3/21/2023 访问量:317

问:

我们的系统(显然)有太多打开的文件:

Error: EMFILE: too many open files

我们是否应该在以下时间后显式关闭文件:

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

似乎规范的答案(比如这个)没有提到它。

打字稿 文件 io fclose

评论

0赞 Robert Rendell 3/21/2023
我相信您在使用时不需要关闭它(tutorialspoint.com/nodejs/...您使用的是哪个版本的节点?fs.readFileSync
0赞 OrenIshShalom 3/21/2023
@RobertRendell,v18.12.1
0赞 Robert Rendell 3/21/2023
我也很难理解为什么你会在使用 .您是否正在读取代码中其他位置的文件?readFileSync
1赞 OrenIshShalom 3/21/2023
你的意思是阅读其他文件,对吧?不一定是相同的(相同的,我敢肯定答案是否定的)

答:

1赞 OrenIshShalom 3/21/2023 #1

这是一个将 with 和 包装起来的解决方案:readFileSyncopenSynccloseSync

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)

它打开 + 读取 + 关闭 100,000 个文件,没有任何问题:

$ grep -rn "\"name\": " input.json | wc -l
100001
$ npx tsc main.ts                         
$ node ./main.js                          
100001

评论

0赞 Robert Rendell 3/21/2023
啊修好了!干得好