无法读取heroku中保存的文件

我在heroku上使用NodeJS。

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

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

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)); }); 

这在我的本地主机上运行良好。

但是,在部署到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 

我正在使用process.cwd()来确保path正确使用。 但即使这样也没有帮助。 根据heroku文档,我可以自由地在应用程序目录中创build文件,这是我正在做的。 但我不明白为什么这是无法读取文件…

你在这里描述的错误与/app/temp/不存在一致。 在开始写入之前,您需要创build它。 这个想法是:

 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); 

我使用同步版本的电话仅用于图示目的。 这个代码应该是你的应用程序的启动代码的一部分(而不是被称为每个请求),你应该如何构build它取决于你的具体应用程序。