如何使用Nodejs从docx文件中提取文本

时间:2017-07-06 15:20:05

标签: node.js mammoth

我想从docx文件中提取文本,我尝试过使用猛犸象

var mammoth = require("mammoth");
mammoth.extractRawText({path: "./doc.docx"})
    .then(function(result){
        var text = result.value; // The raw text 

        //this prints all the data of docx file
        console.log(text);

        for (var i = 0; i < text.length; i++) {
            //this prints all the data char by char in separate lines
            console.log(text[i]);
        }
        var messages = result.messages;
    })
    .done();

但问题在于,在这个for循环中,我想逐行而不是char的char,请在这里帮助我,或者你知道其他任何方法吗?

3 个答案:

答案 0 :(得分:1)

您可以使用any-text

用法很简单:

var reader = require('any-text');

reader.getText(`path-to-file`).then(function (data) {
  console.log(data);
});

答案 1 :(得分:0)

一种方法是获取整个文本,然后按'\n'分割:

import superagent from 'superagent';
import mammoth from 'mammoth';

const url = 'http://www.ojk.ee/sites/default/files/respondus-docx-sample-file_0.docx';

const main = async () => {

  const response = await superagent.get(url)
    .parse(superagent.parse.image)
    .buffer();

  const buffer = response.body;

  const text = (await mammoth.extractRawText({ buffer })).value;
  const lines = text.split('\n');

  console.log(lines);
};

main().catch(error => console.error(error));

答案 2 :(得分:0)

    var mammoth = require("mammoth");
var path = require("path");

var filePath = path.join(__dirname,'./doc.docx');

mammoth.extractRawText({path: filePath})
    .then(function(result){
        var text = result.value; // The raw text

        //this prints all the data of docx file
        //console.log(text);
        console.log('------------------------------');
        var textLines = text.split ("\n");

        for (var i = 0; i < textLines.length; i++) {
            //this prints all the data in separate lines
            console.log(textLines[i]);
        }
        var messages = result.messages;
    })
    .done();
相关问题