我的圖書館:使用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