在nodejs文档中,streams部分说我可以执行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'
}
PS: https://www.example.com/path/to/mp4Video.mp4 IS NOT THE ACTUAL URL
发布于 2021-01-31 07:21:14
fs.createReadStream()
不适用于http,只有file://
URL或文件名路径。不幸的是,fs
文档中没有描述这一点,但是如果您查看源代码 for fs.createReadStream()
并遵循它所称的内容,您会发现它最终调用了fileURULtoPath(url)
,如果它不是file:
URL,就会抛出fileURULtoPath(url)
。
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中获取一个读流:
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模块的代码。
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);
});
});
在这两种情况下都可以添加更高级的错误处理。
https://stackoverflow.com/questions/65976322
复制相似问题