2017-12-21 5 views
0

にコールバックを使用してファイルをループ解析PDFは、それの非同期自然とかなり苦労しています。 Nodejs:私はそうノードに新しいです同期

は、私は別のディレクトリ内のディレクトリおよびTXT形式で出力して内部のPDFファイルを解析するスクリプトを作成しようとしています。

これを行うには、fsとpdf2json npmパッケージを使用しています。私は、loopingFiles関数でコールバックとしてparseData関数を渡しています。唯一の問題はノードの非同期性です。

それは同時に、すべてのファイルをループし、出力は最後のファイルのインデックスにごちゃ混ぜに混乱であるだろう。

私は、データが再びループをTXTへの書き込みを解析して終了すると、それが待機する、これは同期などを処理したいと思います。

私は約束を試みたが、無駄にしています。どんな助けでも大歓迎です!

var fs = require('fs'), 
 
PDFParser = require("pdf2json"); 
 

 
let pdfParser = new PDFParser(this,1); 
 

 
var parseData = function(pdf, index) { 
 
    txtFile = "/Users/janet/node/pdf/Destination/".concat(index.toString().concat(".txt")) 
 
    pdfFile = "/Users/janet/node/pdf/Source/".concat(pdf); 
 
    pdfParser.loadPDF(pdfFile); 
 
    // Parsing the pdf file in question 
 
    pdfParser.on("pdfParser_dataError", errData => console.error(errData.parserError)); 
 
    pdfParser.on("pdfParser_dataReady", pdfData => { 
 
     fs.writeFile(txtFile, pdfParser.getRawTextContent()); 
 
}); 
 
    }; 
 

 

 

 
var loopingFiles = function(callback) { 
 
    fs.readdir("/Users/janet/node/pdf/Source", function (err, files) { 
 
    if (err) { 
 
    console.log(err); 
 
    } else { 
 
    files.forEach(function(file, index) { 
 
     callback(file, index); 
 
    }); 
 
    }; 
 
    }); 
 
}; 
 

 

 
loopingFiles(parseData);

答えて

0

このような何か?主な違いは、インデックスとの関数にPDFのアレイ全体を通過し、現在のが

を完了するだけインクリメントインデックスに再びその関数を呼び出している

var fs = require("fs"), 
    PDFParser = require("pdf2json"); 

let pdfParser = new PDFParser(this, 1); 

var parseData = function(pdfs, index = 0) { 
    // finished 
    if (index >= pdfs.length) return; 
    let pdf = pdfs[index]; 
    txtFile = "/Users/janet/node/pdf/Destination/".concat(
    index.toString().concat(".txt") 
); 
    pdfFile = "/Users/janet/node/pdf/Source/".concat(pdf); 
    // Parsing the pdf file in question 
    pdfParser.on("pdfParser_dataError", errData => { 
    console.error(errData.parserError) 
    // not sure if you want to call this here to keep going or not 
    parseData(pdfs, index + 1); 
    }); 
    pdfParser.on("pdfParser_dataReady", pdfData => { 
    fs.writeFile(txtFile, pdfParser.getRawTextContent(), function() { 
     // when we're all done, call this function again, with the index of the next pdf 
     parseData(pdfs, index + 1); 
    }); 
    }); 
    pdfParser.loadPDF(pdfFile); 
}; 

var loopingFiles = function(callback) { 
    fs.readdir("/Users/janet/node/pdf/Source", function(err, files) { 
    if (err) { 
     console.log(err); 
    } else { 
     callback(files, 0); 
    } 
    }); 
}; 

loopingFiles(parseData); 

関連する問題