首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从nodejs中的远程url创建可读流?

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

Stack Overflow用户
提问于 2021-01-31 06:22:29
回答 1查看 21.3K关注 0票数 18

在nodejs文档中,streams部分说我可以执行fs.createReadStream(url || path)。但是,当我真的这么做的时候,它告诉我Error: ENOENT: no such file or directory。我只想把视频从一个可读的流传输到一个可写的流,但是我仍然坚持创建一个可读的流。

我的代码

代码语言:javascript
运行
复制
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)
})

错误:

代码语言:javascript
运行
复制
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'
}

PS: https://www.example.com/path/to/mp4Video.mp4 IS NOT THE ACTUAL URL

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-31 07:21:14

fs.createReadStream()不适用于http,只有file:// URL或文件名路径。不幸的是,fs文档中没有描述这一点,但是如果您查看源代码 for fs.createReadStream()并遵循它所称的内容,您会发现它最终调用了fileURULtoPath(url),如果它不是file: URL,就会抛出fileURULtoPath(url)

代码语言:javascript
运行
复制
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);
}

建议使用got()库从URL中获取一个读流:

代码语言:javascript
运行
复制
const got = require('got');
const mp4Url = 'https://www.example.com/path/to/mp4Video.mp4';

app.get('/video', (req, res) => {
    got.stream(mp4Url).pipe(res);
});

本文中描述的更多示例:如何用Got在Nodejs中流文件下载

您也可以使用普通的http/https模块来获取readstream,但是我发现got()在更高的层次上对于很多http请求都是有用的,所以我就是这样使用的。但是,下面是带有https模块的代码。

代码语言:javascript
运行
复制
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);
    });
});

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

票数 27
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65976322

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档