【问题标题】:Download and save PDF using Deno使用 Deno 下载并保存 PDF
【发布时间】:2021-04-20 16:48:39
【问题描述】:

您好,我想使用 deno 下载 pdf 文件。

我正在使用

export default async function downloadPDF(uid: string): Promise<void> {
   const res = await fetch(`${Deno.env.get('MY_PDF_URL')}/${uid}`);
   const file = await Deno.open(`./pdfs/${uid}.pdf`, { create: true, write: true })

   if (res?.body) {
      for await(const chunk of res.body) {
         await Deno.writeAll(file, chunk);
      }
   }
   file.close();
}

我使用的命令是deno run --allow-net --allow-read --allow-write --allow-env --allow-run main.ts。所以我认为我没有在这里设置正确的权限。

但是我得到了错误

error: Uncaught (in promise) PermissionDenied: Permission denied (os error 13)
api_1  |    const file = await Deno.open(`./pdfs/${uid}.pdf`, { create: true, write: true })
api_1  |                 ^
api_1  |     at unwrapOpResult (deno:core/core.js:100:13)
api_1  |     at async Object.open (deno:runtime/js/40_files.js:46:17)
api_1  |     at async downloadPDF (file:///app/downloadPDF.ts:3:17)

这可能是什么问题?我正在使用Dockerfile

FROM hayd/alpine-deno:1.9.0

EXPOSE 1993

WORKDIR /app

USER deno

COPY deps.ts .
RUN deno cache deps.ts

COPY . .
RUN deno cache main.ts

CMD [run --allow-net --allow-read --allow-write --allow-env --allow-run main.ts]

运行这个应用程序。

【问题讨论】:

    标签: deno


    【解决方案1】:
    import { readerFromStreamReader } from "https://deno.land/std@0.93.0/io/mod.ts";
    
    export default async function downloadPDF(uid: string): Promise<void> {
       const res = await fetch(`https://example.com/pdfs/${uid}`);
    
       if (res.status !== 200) {
          console.error(`response status was ${res.status}, this is not handled.`);
    
          return;
       }
    
    
       // we don't want to download existing files
       if (await fileExists(`/html/${uid}.html`)) {
          console.info(`${uid}.html already exists, skipping...`);
    
          return;
       }
    
       const file = await Deno.open(`/pdfs/${uid}.pdf`, { create: true, write: true, read: true })
    
       if (res?.body) {
          const reader = readerFromStreamReader(res.body.getReader());
          await Deno.copy(reader, file);
       }
       file.close();
    }
    

    我在问题中发布的错误是由于我的Dockerfile 中的 deno 用户的文件权限而发生的。只需删除用户即可解决问题。但是,如果将其用于生产,则正确设置权限会更好。

    【讨论】:

      猜你喜欢
      • 2020-12-17
      • 2021-09-17
      • 1970-01-01
      • 2021-08-23
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多