此程序会导致内存泄漏吗?

问题描述 投票:0回答:1

我似乎无法找出导致内存泄漏的原因。我收到“堆内存不足”错误。我试图将所有没有用的变量设置为null,但没有用。我尝试使用简单的forEach函数而不是使用each中的async.js函数,但这也没有用。在任务管理器中查看应用程序的内存使用情况时,其运行时间越长,消耗的内存就越高。但我似乎无法弄清哪些地方没有清理或收集垃圾。

const fs = require('fs')

const mj = require('mathjax-node-sre')
const each = require('async/each')
const colors = require('colors')
const cliProgress = require('cli-progress')
const { JSDOM } = require('jsdom')

mj.config({ displayErrors: false })

console.log('')

const progressBar = new cliProgress.SingleBar({
  format: '  MathML to SRE  ' + colors.cyan('{bar}') + '  {percentage}%  |  {value}/{total} Files',
  barCompleteChar: '\u2588',
  barIncompleteChar: '\u2591',
  hideCursor: true
})

let files = fs.readdirSync('C:/Users/koliva/Desktop/xml2/').filter(file => file.endsWith('\.xml') && !file.endsWith('_sre\.xml'))
let mjErrors = []

progressBar.start(files.length, 0)

each(files, (mml, callback) => {
  try {
    let inputFileName = mml
    let outpuFileName = 'C:/Users/koliva/Desktop/xml2/' + mml.replace('\.xml', '_sre.xml')

    mml = fs.readFileSync('C:/Users/koliva/Desktop/xml2/' + mml, 'utf8')

    mj.typeset({ math: mml, format: 'MathML', svg: true }, data => {
      let sre = new JSDOM(data.svg).window.document.getElementsByTagName('title')[0].innerHTML

      mml = new JSDOM(mml)
      mml.window.document.getElementsByTagName('mml:math')[0].setAttribute('alttext', sre)

      fs.writeFileSync(outpuFileName, mml.serialize().replace(/<\/?body>|<\/?html>|<\/?head>/g, ''))
      progressBar.increment()
      if (data.errors) {
        mjErrors = mjErrors.concat({ 'name': inputFileName, 'errors': data.errors })
      }
      callback()
    })
  } catch (error) {
    callback(error)
  }
}, (err) => {
     // do something
})

node.js asynchronous memory-leaks heap-memory async.js
1个回答
0
投票

nodejs使用的V8引擎在64位计算机上的默认内存限制为~1.5GB。即使系统上有更多可用内存,如果堆分配增加1.5GB,默认情况下,nodejs也会抛出Heap out of memory错误。

[这样运行应用程序时,有一种简单的方法可以通过传递max_old_space_size标志来增加默认内存限制:

#increase to 4gb
node --max-old-space-size=4096 index.js

[如果您想研究堆内存的分配位置和方式,以及是否存在内存泄漏,则可以通过使用chrome的inspect工具检查您的应用程序来轻松实现。

只需使用node --inspect server.js运行您的应用,然后导航至chrome://inspect。在这里,您可以查看随时间推移使用的堆快照。更多详细信息here

© www.soinside.com 2019 - 2024. All rights reserved.