提问人:OrenIshShalom 提问时间:3/21/2023 更新时间:3/21/2023 访问量:317
在 readFileSync 之后显式关闭文件
explicitly closing a file after readFileSync
问:
我们的系统(显然)有太多打开的文件:
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?
}
似乎规范的答案(比如这个)没有提到它。
答:
1赞
OrenIshShalom
3/21/2023
#1
这是一个将 with 和 包装起来的解决方案:readFileSync
openSync
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)
它打开 + 读取 + 关闭 100,000 个文件,没有任何问题:
$ grep -rn "\"name\": " input.json | wc -l
100001
$ npx tsc main.ts
$ node ./main.js
100001
评论
0赞
Robert Rendell
3/21/2023
啊修好了!干得好
上一个:使用 fclose 的奇怪行为
评论
fs.readFileSync
v18.12.1
readFileSync