无法在heroku中读取已保存的文件

时间:2021-07-19 09:00:02

I am using NodeJS on heroku.

我在heroku上使用NodeJS。

I read a file from another server and save it into my application in the /temp directory. Next, I read the same file to pass it on to my client.

我从另一台服务器读取文件并将其保存到/ temp目录中的应用程序中。接下来,我读取相同的文件将其传递给我的客户端。

The code that saves the file and then subsequently reads it is:

保存文件然后随后读取的代码是:

http.request(options, function (pdfResponse) {
    var filename = Math.random().toString(36).slice(2) + '.pdf',
        filepath = nodePath.join(process.cwd(),'temp/' + filename);

    pdfResponse.on('end', function () {
        fs.readFile(filepath, function (err, contents) {
            //Stuff to do after reading
        });
    });

    //Read the response and save it directly into a file
    pdfResponse.pipe(fs.createWriteStream(filepath));
});

This works well on my localhost.

这在我的localhost上运行良好。

However, when deployed to heroku, I get the following error:

但是,当部署到heroku时,我收到以下错误:

events.js:72
throw er; // Unhandled 'error' event
Error: ENOENT, open '/app/temp/nvks0626yjf0qkt9.pdf'
Process exited with status 8
State changed from up to crashed

I am using process.cwd() to ensure that the path is correctly used. But even then it did not help. As per the heroku documentation, I am free to create files in the applications directory, which I am doing. But I can't figure out why this is failing to read the file...

我正在使用process.cwd()来确保正确使用该路径。但即便如此,它也无济于事。根据heroku文档,我可以*地在应用程序目录中创建文件,我正在这样做。但我无法弄清楚为什么这是无法读取文件...

1 个解决方案

#1


10  

The error you describe there is consistent with /app/temp/ not existing. You need to create it before you start writing in it. The idea is:

您在此处描述的错误与/ app / temp / not existing一致。您需要在开始编写之前创建它。这个想法是:

var fs = require("fs");
var path = require("path");
var temp_dir = path.join(process.cwd(), 'temp/');

if (!fs.existsSync(temp_dir))
    fs.mkdirSync(temp_dir);

I've used the sync version of the calls for illustrations purposes only. This code should be part of the start up code for your app (instead of being called for each request) and how you should structure it depends on your specific application.

我使用同步版本的电话仅用于说明目的。此代码应该是应用程序启动代码的一部分(而不是为每个请求调用)以及如何构建它取决于您的特定应用程序。

#1


10  

The error you describe there is consistent with /app/temp/ not existing. You need to create it before you start writing in it. The idea is:

您在此处描述的错误与/ app / temp / not existing一致。您需要在开始编写之前创建它。这个想法是:

var fs = require("fs");
var path = require("path");
var temp_dir = path.join(process.cwd(), 'temp/');

if (!fs.existsSync(temp_dir))
    fs.mkdirSync(temp_dir);

I've used the sync version of the calls for illustrations purposes only. This code should be part of the start up code for your app (instead of being called for each request) and how you should structure it depends on your specific application.

我使用同步版本的电话仅用于说明目的。此代码应该是应用程序启动代码的一部分(而不是为每个请求调用)以及如何构建它取决于您的特定应用程序。