2017-12-21 19 views
0

노드를 처음 사용하므로 비동기 특성으로 인해 많은 어려움을 겪고 있습니다.Nodejs : 콜백을 사용하여 파일을 반복하고 PDF에서 코드를 콜백 함

디렉토리에서 pdfs를 구문 분석하고 다른 디렉토리에서 txt 형식으로 출력하는 스크립트를 만들려고합니다.

이렇게하려면 fs 및 pdf2json npm 패키지를 사용하고 있습니다. parseData 함수를 loopingFiles 함수의 콜백으로 전달하고 있습니다. 유일한 문제는 노드의 비동기 성격입니다.

동시에 모든 파일을 반복하므로 출력이 마지막 파일 인덱스에서 뒤죽박죽입니다.

데이터를 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);