node.js - 从 Heroku 服务器删除上传的文件

标签 node.js heroku

我创建了一个可以上传文件的项目,例如 Dropbox,部署到 Heroku 并且工作正常,但现在我想从 Heroku 服务器删除该文件。

我从数据库中删除了具有关系的路径,但是我尝试了很多方法从服务器中删除文件但没有成功,最后一个通过fs.unlink(),这似乎是最好的使用:

//working example
const file = {url: 'https://mobox-app.herokuapp.com/files/dbd3917046ec3075f2a424e07c9a39aa-1*hoSDm9oecgsKShbAroI2XQ.jpeg'} 

async deleteFile(req, res){

        const file = await File.findById(req.body.fileId),
              fileId = req.body.fileId       

        await File.deleteOne( {_id: fileId}).then(

            fs.unlink(file.url, (err) => {

                if (err) {

                  console.error(err)

                  return

                }

            })

        )
}

这是heroku日志给我的:

2019-06-28T16:01:43.514606+00:00 app[web.1]: { [Error: ENOENT: no such file or directory, unlink 'https://mobox-app.herokuapp.com/files/dbd3917046ec3075f2a424e07c9a39aa-1*hoSDm9oecgsKShbAroI2XQ.jpeg']

2019-06-28T16:01:43.514645+00:00 app[web.1]:   errno: -2,

2019-06-28T16:01:43.514648+00:00 app[web.1]:   code: 'ENOENT',

2019-06-28T16:01:43.514650+00:00 app[web.1]:   syscall: 'unlink',

2019-06-28T16:01:43.514652+00:00 app[web.1]:   path:

2019-06-28T16:01:43.514654+00:00 app[web.1]:    'https://mobox-app.herokuapp.com/files/dbd3917046ec3075f2a424e07c9a39aa-1*hoSDm9oecgsKShbAroI2XQ.jpeg' }

它找不到路径,如果我仅将 '/files/fileName.ext' 或仅将 'fileName.ext' 作为 则相同文件.url。我怎样才能删除这些文件?

最佳答案

I've created a project that I can upload files, like Dropbox, deployed to Heroku and it works fine, but now I want to delete the file from Heroku server.

您可能需要仔细观察并思考“工作正常”意味着什么。

Heroku 的文件系统 is ephemeral :您所做的任何更改(例如存储文件)都将在下次 dyno 重新启动时丢失。这个happens frequently (每天至少一次)。无论您是否愿意,您上传的内容都会被自动删除。

Heroku recommends将用户上传的内容存储在 Amazon S3 等第三方服务上。您必须迁移到类似的东西才能使存储部分正常工作,并且当您想要删除文件时,您必须使用您选择的服务提供的任何工具。

关于node.js - 从 Heroku 服务器删除上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56810275/

相关文章:

node.js - 增加 Google Actions 服务器端的超时时间?

javascript - MongoDB,如果新值不为空,则更新集合字段

node.js - 使用 nodemailer 发送电子邮件在 Heroku 上失败

node.js - NestJS Mongoose 扩展架构并覆盖父级的属性

node.js - 具有多个 api 调用的异步/promise

node.js - 如何计算sequelize js中的关联

typescript - 为什么 tsc 不在 Heroku 中运行?

javascript - Mongoose 不会在生产 (Heroku) 上填充 (.populate()),但可以在本地工作

node.js - Heroku 部署错误 : Cannot find module './errors/cast'

node.js - 无法使用 npm 重建依赖项