读取目录中的docx文件并在节点中将内容连接在一起



读取一个目录中的所有文件并返回该目录的每个docx文件中的所有内容需要该代码。

我使用glob和猛犸库分别读取目录和docx文件。但是,我想将每个文件的内容连接到一个更大的内容中。但由于node是异步的,所以我编写的代码在读取每个文件之前都会将空内容传递给我。

var mammoth = require("mammoth");
var glob = require("glob");
function readAllFiles(dir){
var data_collection = '';
return new Promise(async(resolve, reject) => {
// reading the directory
glob(dir,  function (er, files) { 
console.log(files);
// for each file in the directory read its content
_.map(files, function(file){
mammoth.extractRawText({path: file})
.then(function(result){
var text = result.value; // The raw text
var messages = result.messages;
text = text.replace(/(^[ t]*n)/gm, "").replace('r', '').replace('n', '');
console.log('extractRawText',text);
// concat the small content into big content
data_collection = data_collection + " "+text;
})
.done();
});
resolve(data_collection);
});
});
}

我该如何解决这个问题?

_.map是同步的。它不等待巨大的承诺得到解决。行resolve(data_collection);将在_.map之后且在巨大的承诺解析之前立即执行。这就是data_collection为空的原因。

你可以使用类似的东西

var mammoth = require("mammoth");
var glob = require("glob");
function readAllFiles(dir){
return new Promise((resolve, reject) => {
glob(dir, (err, files) => {
if(err) {
return reject(err)
}
return Promise.all(files.map((file) => mammoth.extractRawText({ path: file })))
.then((results) => {
let data = ''
results.forEach((result) => {
const value = result.value.replace(/(^[ t]*n)/gm, "").replace('r', '')
data = data.concat(value)
})
resolve(data)
})
.catch(reject)
})
})
}
async function test() {
const data = await readAllFiles('./test/**/*.docx') // All my docx files are in the test directory
console.log(data) // Print data
}
test()

请注意,这将并行执行mammoth.extractRawText函数调用。如果需要限制同时并行调用的数量,可以使用async.mapLimit.

最新更新