Read json file content with require vs fs.readFile

前端 未结 7 2020
说谎
说谎 2020-11-30 03:46

Suppose that for every response from an API, i need to map the value from the response to an existing json file in my web application and display the value from the json. Wh

7条回答
  •  广开言路
    2020-11-30 04:13

    I only want to point out that it seems require keeps the file in memory even when the variables should be deleted. I had following case:

    for (const file of fs.readdirSync('dir/contains/jsons')) {
      // this variable should be deleted after each loop
      // but actually not, perhaps because of "require"
      // it leads to "heap out of memory" error
      const json = require('dir/contains/jsons/' + file);
    }
    
    for (const file of fs.readdirSync('dir/contains/jsons')) {
      // this one with "readFileSync" works well
      const json = JSON.parse(fs.readFileSync('dir/contains/jsons/' + file));
    }
    

    The first loop with require can't read all JSON files because of "heap out of memory" error. The second loop with readFile works.

提交回复
热议问题