如何从nodejs中的远程url创建可读流?

问题描述

在 nodejs 文档中,流部分说我可以做 ScrollConfiguration( behavior: ScrollBehavior(),// From this behavIoUr you can change the behavIoUr child: GlowingOverscrollIndicator( axisDirection: AxisDirection.down,color: Colors.yellow,// You can change your splash color child: ListView.builder( ..... ),),); 。 但是,当我真正这样做时,它告诉我 fs.createReadStream(url || path)。 我只是想将视频从可读流传输到可写流,但我一直坚持创建可读流。

我的代码

Error: ENOENT: no such file or directory

错误

const express = require('express')
const fs = require('fs')
const url = 'https://www.example.com/path/to/mp4Video.mp4'
const port = 3000

app.get('/video',(req,res) => {
    const readable = fs.createReadStream(url)
})
app.listen(port,() => {
    console.log('listening on port ' + port)
})

listening on port 3000 events.js:291 throw er; // Unhandled 'error' event ^ Error: ENOENT: no such file or directory,open 'https://www.example.com/path/to/mp4Video.mp4' Emitted 'error' event on ReadStream instance at: at internal/fs/streams.js:136:12 at FSReqCallback.oncomplete (fs.js:156:23) { errno: -2,code: 'ENOENT',syscall: 'open',path: 'https://www.example.com/path/to/mp4Video.mp4' }

解决方法

fs.createReadStream() 不适用于 http URL 仅 file:// URL 或文件名路径。不幸的是,这在 fs 文档中没有描述,但是如果您查看 fs.createReadStream()source code 并遵循它的调用,您会发现它最终调用了 {{1}如果它不是 fileURULtoPath(url) 网址,则会抛出。

file:

建议使用 function fileURLToPath(path) { if (typeof path === 'string') path = new URL(path); else if (!isURLInstance(path)) throw new ERR_INVALID_ARG_TYPE('path',['string','URL'],path); if (path.protocol !== 'file:') throw new ERR_INVALID_URL_SCHEME('file'); return isWindows ? getPathFromURLWin32(path) : getPathFromURLPosix(path); } 库从 URL 获取读取流:

got()

本文中描述的更多示例:How to stream file downloads in Nodejs with Got


您也可以使用普通的 const got = require('got'); const mp4Url = 'https://www.example.com/path/to/mp4Video.mp4'; app.get('/video',(req,res) => { got.stream(mp4Url).pipe(res); }); 模块来获取读取流,但我发现 http/https 在更高级别通常对许多 http 请求事物有用,所以这就是我使用的。但是,这是带有 https 模块的代码。

got()

可以为这两种情况添加更高级的错误处理。