如何在 NodeJS Web 应用程序中存储和访问大文件

How to Store and Access Large Files in NodeJS Web Application

如果我想允许用户在 post 中上传视频,那么最好的存储方式是什么以便我以后可以访问它?我目前只是使用 INSERT 查询将其上传到 PostGres SQL 数据库字段,但速度非常慢。

是否有其他方法或最佳实践来存储这样的大文件并快速有效地访问它?

var video = videoFile ? "'\x" + videoFile.buffer.toString('hex') + "'" : "NULL";
let insertQuery = "INSERT INTO posts (video) VALUES(" + video + ") RETURNING *";

以上是我现在用来将文件插入数据库的代码。

不要将整个视频存入数据库。下面这两个步骤可能是更好的解决方案:

1) 上传视频文件到云存储。参见 Google Cloud Strage and Amazon S3。还有许多其他选项。自己去对比一下吧。

2) 您将有一个 link 或 ID(或 S3 中的密钥)来访问文件。将所有这些 link 或 ID 存储到您的数据库中。请看看这个GCS doc and this S3 question.

此外,利用 non-blocking I/O,这是 node.js 的优点。在你的情况下,你可以尝试这样的事情:

let insertQuery;
let promisesList=[];

for(let vid of videoIds){
    insertQuery = "INSERT INTO posts (videoId) VALUES() RETURNING *";
    promisesList.push(client.query(query,[vid]));
}
await Promise.all();