我的图书馆:使用Javascript - .MAP运行内存
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('graceful-fs'));
const path = require('path');
const xml2js = Promise.promisifyAll(require('xml2js'));
我有大量的我想要解析XML文件。我能够创造的路径的数组来使用此功能的所有文件:
function getFileNames(rootPath) {
// Read content of path
return fs.readdirAsync(rootPath)
// Return all directories
.then(function(content) {
return content.filter(function(file) {
return fs.statSync(path.join(rootPath, file)).isDirectory();
});
})
// For every directory
.map(function(directory) {
// Save current path
let currentPath = path.join(rootPath, directory);
// Read files in the directory
return fs.readdirAsync(currentPath)
// Filter out the XMLs
.filter(function(file) {
return path.extname(file) === '.XML';
})
// Return path to file
.map(function(file) {
return path.join(rootPath, directory, file);
});
})
// Flatten array of results
.reduce(function(a, b) {
return a.concat(b);
});
}
,现在我想走线槽的每一个文件,并解析它。
我有2个功能可以这样做:
function openFile(filePath) {
return fs.readFileAsync('./' + filePath)
.then(function(fileData) {
return fileData;
});
}
function parseFile(data) {
return xml2js.parseStringAsync(data)
.then(function(xmlObject) {
return xmlObject;
});
}
现在,当我把这种与.MAP(该GetFileNames
函数输出的阵列超过20K串与文件路径)函数:
getFileNames('./XML')
.map(function(file) {
openFile(file)
.then(function(data) {
parseFile(data)
.then(function(object) {
console.log(object);
});
});
});
我得到一个javascript堆内存不足的错误:
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
但是当我运行该功能由路径传递到实际的文件中的单个时间:
openFile('./XML/2016-10-1/EUROTIPOLD2016-10-1T00-00-22.5756240530.XML')
.then(function(data) {
parseFile(data)
.then(function(object) {
console.log(object);
});
});
我得到所需的输出。
我在做什么错?
所以你说,当你以某种方式使用varaible,而不是它的工作原理硬编码字符串的??? – epascarello
对不起,编辑了这个问题。我说当我运行函数一次没有.map函数时它的工作原理(通过传递一个字符串与文件的路径)。当我在.map函数中运行它时,内存不足。 –
您尝试打开多少个文件?不要忘记异步函数,Node.js尝试同时打开所有文件,而不是一个接一个地打开。 – Fefux