将存储在内存中的字符串传递给pdftotext,antiword,catdoc等

6 pdf text child-process node.js

是否可以调用pdftotext,antiword,catdoc(文本提取器脚本)等CLI工具传递字符串而不是文件?

目前,我阅读了调用pdftotext的PDF文件child_process.spawn.我生成一个新进程并将结果存储在一个新变量中.一切正常.

我想传递binary一个fs.readFile而不是文件本身:

fs.readFile('./my.pdf', (error, binary) => {
    // Call pdftotext with child_process.spawn passing the binary.
    let event = child_process.spawn('pdftotext', [
        // Args here!
    ]);
});
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Dar*_*ght 2

如果命令可以处理管道输入,这绝对是可能的。

spawn返回一个ChildProcess对象,您可以通过写入其stdin将内存中的字符串(或二进制)传递给它。该字符串应首先转换ReadableStream ,然后您可以通过pipeline将字符串写入stdinCLI 。

createReadStream从文件创建ReadableStream 。

以下示例下载 pdf 文件并将内容通过管道传输到pdftotext,然后显示结果的前几个字节。

const source = 'http://static.googleusercontent.com/media/research.google.com/en//archive/gfs-sosp2003.pdf'
const http = require('http')
const spawn = require('child_process').spawn

download(source).then(pdftotext)
.then(result => console.log(result.slice(0, 77)))

function download(url) {
  return new Promise(resolve => http.get(url, resolve))
}

function pdftotext(binaryStream) {
  //read input from stdin and write to stdout
  const command = spawn('pdftotext', ['-', '-'])
  binaryStream.pipe(command.stdin)

  return new Promise(resolve => {
    const result = []
    command.stdout.on('data', chunk => result.push(chunk.toString()))
    command.stdout.on('end', () => resolve(result.join('')))
  })
}
Run Code Online (Sandbox Code Playgroud)

由于 CLI 没有读取选项stdin,您可以使用命名管道

编辑:添加另一个带有命名管道的示例。

创建命名管道后,您可以像文件一样使用它们。以下示例创建临时命名管道来发送输入和获取输出,并显示结果的前几个字节。

const fs = require('fs')
const spawn = require('child_process').spawn

pipeCommand({
  name: 'wvText',
  input: fs.createReadStream('document.doc'),
}).then(result => console.log(result.slice(0, 77)))

function createPipe(name) {
  return new Promise(resolve =>
    spawn('mkfifo', [name]).on('exit', () => resolve()))
}

function pipeCommand({name, input}) {
  const inpipe = 'input.pipe'
  const outpipe = 'output.pipe'
  return Promise.all([inpipe, outpipe].map(createPipe)).then(() => {
    const result = []
    fs.createReadStream(outpipe)
    .on('data', chunk => result.push(chunk.toString()))
    .on('error', console.log)

    const command = spawn(name, [inpipe, outpipe]).on('error', console.log)
    input.pipe(fs.createWriteStream(inpipe).on('error', console.log))
    return new Promise(resolve =>
      command.on('exit', () => {
        [inpipe, outpipe].forEach(name => fs.unlink(name))
        resolve(result.join(''))
      }))
  })
}
Run Code Online (Sandbox Code Playgroud)