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

Node.js 如何从nodejs中的远程url创建可读流?,node.js,video-streaming,nodejs-stream,nodejs-server,Node.js,Video Streaming,Nodejs Stream,Nodejs Server,在nodejs文档中,streams部分说我可以执行fs.createReadStreamurl | | path。 但是,当我实际这样做时,它告诉我错误:enoint:没有这样的文件或目录。 我只想将视频从可读流传输到可写流,但我一直在创建可读流 我的代码: 错误: 附言:https://www.example.com/path/to/mp4Video.mp4 不是实际的URLfs。createReadStream不适用于仅http URL文件://URL或文件名路径。不幸的是,fs文档中没有

在nodejs文档中,streams部分说我可以执行fs.createReadStreamurl | | path。 但是,当我实际这样做时,它告诉我错误:enoint:没有这样的文件或目录。 我只想将视频从可读流传输到可写流,但我一直在创建可读流

我的代码:

错误:

附言:https://www.example.com/path/to/mp4Video.mp4 不是实际的URL

fs。createReadStream不适用于仅http URL文件://URL或文件名路径。不幸的是,fs文档中没有描述这一点,但是如果您查看for fs.createReadStream并遵循它的调用,您会发现它最终会调用FileUrultPathURL,如果它不是file:URL,则会抛出

建议使用get库从URL获取readstream:

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模块来获取readstream,但是我发现在更高的级别上,对于许多http请求的事情来说,它通常是有用的,所以这就是我所使用的。但是,下面是https模块的代码

const https = require('https');
const mp4Url = 'https://www.example.com/path/to/mp4Video.mp4';

app.get("/", (req, res) => {
    https.get(mp4Url, (stream) => {
        stream.pipe(res);
    });
});

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

require'https'版本运行良好,无需安装其他第三方软件包。https.get是否返回流?那么我可以做一些类似const myStream=https.getmp4Url的事情吗?我希望最终将其用于fluent ffmpeg。@Optymystyc-正如您在我的回答的最后一个代码块中所看到的,它不会返回流,而是将流提供给您传递它的回调。
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);
}
const got = require('got');
const mp4Url = 'https://www.example.com/path/to/mp4Video.mp4';

app.get('/video', (req, res) => {
    got.stream(mp4Url).pipe(res);
});
const https = require('https');
const mp4Url = 'https://www.example.com/path/to/mp4Video.mp4';

app.get("/", (req, res) => {
    https.get(mp4Url, (stream) => {
        stream.pipe(res);
    });
});