如何使用nodejs流式传输不同的本地视频并表达

发布于 2025-01-21 20:45:11 字数 1879 浏览 2 评论 0原文

我想将不同的用户选择视频流到我的前端。为此,我正在使用nodejs和Express。应显示视频的 - 元素的来源是'http:// localhost:4201/video'。

我用来流式传输视频的代码看起来像这样:

async function loadLocalVideo(_, filePath) {
    if (!filePath) {
        console.log('No file selected');
        return;
    } else {
        fs.access(filePath, (err) => {
            if (err) {
                console.log(`File does not exist at path ${filePath}`);
                return;
            }
        });
    }

    expressApp.get('/video', function (req, res) {
        const path = filePath;
        const stat = fs.statSync(path);
        const fileSize = stat.size;
        const range = req.headers.range;

        if (range) {
            const parts = range.replace(/bytes=/, '').split('-');
            const start = parseInt(parts[0], 10);
            const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;

            if (start >= fileSize) {
                res.status(416).send(
                    'Requested range not satisfiable\n' + start + ' >= ' + fileSize
                );
                return;
            }

            const chunksize = end - start + 1;
            const file = fs.createReadStream(path, { start, end });
            const head = {
                'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                'Accept-Ranges': 'bytes',
                'Content-Length': chunksize,
                'Content-Type': 'video/mp4',
            };

            res.writeHead(206, head);
            file.pipe(res);
        } else {
            const head = {
                'Content-Length': fileSize,
                'Content-Type': 'video/mp4',
            };
            res.writeHead(200, head);
            fs.createReadStream(path).pipe(res);
        }
    });
}

但是,当我想流式传输另一个视频并再次调用相同的功能时,但是使用不同的filepath-param,同一视频会继续播放。如何流式传输另一个视频并在元素中显示?

I would like to stream different user-selected videos to my front-end. For this I am using NodeJS and Express. The source of the -element in which the video should be displayed is 'http://localhost:4201/video'.

The code I am using to stream the video looks like this:

async function loadLocalVideo(_, filePath) {
    if (!filePath) {
        console.log('No file selected');
        return;
    } else {
        fs.access(filePath, (err) => {
            if (err) {
                console.log(`File does not exist at path ${filePath}`);
                return;
            }
        });
    }

    expressApp.get('/video', function (req, res) {
        const path = filePath;
        const stat = fs.statSync(path);
        const fileSize = stat.size;
        const range = req.headers.range;

        if (range) {
            const parts = range.replace(/bytes=/, '').split('-');
            const start = parseInt(parts[0], 10);
            const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;

            if (start >= fileSize) {
                res.status(416).send(
                    'Requested range not satisfiable\n' + start + ' >= ' + fileSize
                );
                return;
            }

            const chunksize = end - start + 1;
            const file = fs.createReadStream(path, { start, end });
            const head = {
                'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                'Accept-Ranges': 'bytes',
                'Content-Length': chunksize,
                'Content-Type': 'video/mp4',
            };

            res.writeHead(206, head);
            file.pipe(res);
        } else {
            const head = {
                'Content-Length': fileSize,
                'Content-Type': 'video/mp4',
            };
            res.writeHead(200, head);
            fs.createReadStream(path).pipe(res);
        }
    });
}

However, when I want to stream a different video and call the same function again but with a different filePath-param the same video keeps playing. How can I stream another video and display it in the -element?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

滴情不沾 2025-01-28 20:45:11

我认为您是在说您正在使用相同的文件名和路径,但希望后端服务器更改流向客户端的实际内容。

这种方法可能会使服务器下游的缓存感到困惑 - 即网络或浏览器缓存可能无法识别文件已更改,并且可以简单地使用缓存的版本。

某些CDN将允许您添加Edge功能以拦截请求,然后确定要返回的许多选项中的哪一个,或者您可以禁用缓存,但我怀疑这些方法可能过于复杂。

如果您想要的只是能够在网页上的视频元素中显示不同的视频,那么简单地更改页面本身上视频上的源属性,然后在视频元素上调用load()页。

I think you are saying that you are using the same file name and path but want the backend server to change the actual contents that are streamed to the client.

This approach may confuse the caching downstream of your server - i.e. the network or browser cache may not recognise that the file has changed and it may simply serve the cached versions.

Some CDN's will allow you add edge functionality to intercept a request and then decide which of a number of options you want to return, or you could disable caching but I suspect these approaches might be overly complex.

If all you want is to be able to display different videos in a video element on your web page, it may be easier to simply change the source attribute on the video on the page itself and then call load() on the video element on the page.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文