Nodejs + PhantomJS in Docker: Error: spawn - ENOENT

Nodejs + PhantomJS in Docker: Error: spawn - ENOENT

我正在开发一个使用 html-pdf 的 Node.js 应用程序,它在给定 html 字符串的情况下创建 pdf 文件时使用 PhantomJS

一切正常,但是当我想在 Docker 中构建应用程序时,出现此错误:

ERROR: Error: spawn /usr/src/app/node_modules/phantomjs-prebuilt/lib/phantom\bin\phantomjs.exe ENOENT
events.js:291
throw er; // Unhandled 'error' event
Error: write EPIPE
at afterWriteDispatched (internal/stream_base_commons.js:156:25)
at writeGeneric (internal/stream_base_commons.js:147:3)
at Socket._writeGeneric (net.js:785:11)
at Socket._write (net.js:797:8)
at writeOrBuffer (_stream_writable.js:352:12)
at Socket.Writable.write (_stream_writable.js:303:10)
at PDF.PdfExec [as exec] (/usr/src/app/node_modules/html-pdf/lib/pdf.js:141:15)
at PDF.PdfToFile [as toFile] (/usr/src/app/node_modules/html-pdf/lib/pdf.js:83:8)
at /usr/src/app/src/createPDF.js:87:42
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3)
Emitted 'error' event on Socket instance at:
at emitErrorNT (internal/streams/destroy.js:100:8)
at emitErrorCloseNT (internal/streams/destroy.js:68:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  errno: -32,
  code: 'EPIPE',
  syscall: 'write'
}

这是我正在使用的Dockerfile

FROM node:latest
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY . .  

RUN npm install --production

RUN wget -O /tmp/phantomjs-2.1.1-linux-x86_64.tar.bz2 https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
RUN mkdir -p /usr/local/lib/node_modules/phantomjs/lib/phantom/
RUN tar xvjf /tmp/phantomjs-2.1.1-linux-x86_64.tar.bz2 -C /tmp/phantomjs
RUN mv /tmp/phantomjs/phantomjs-2.1.1-linux-x86_64/* /usr/local/lib/node_modules/phantomjs/lib/phantom/
RUN rm -rf /tmp/phantomjs-2.1.1-linux-x86_64.tar.bz && rm -rf /tmp/phantomjs

EXPOSE 8080
CMD ["npm","run","serve"]

我不想手动安装 PhantomJS 但这是我在网上找到的唯一解决方案。

我也看了其他问题,试过在选项里把phantompath传过去,没成功。

对于将来遇到此问题的任何人,以下是我设法解决此问题的方法:

FROM node:latest
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY . .  

RUN npm install --production

RUN npm install -g phantomjs --unsafe-perm

EXPOSE 8080
CMD ["npm","run","serve"]

然后在options using requireg传递phantomjs的全局路径:

var options = { phantomPath: require('requireg')('phantomjs').path }