带有缓冲区"fs.statSync"“错误:路径必须是不包含空字节的字符串" [英] fs.statSync with Buffer "Error: Path must be a string without null bytes"
问题描述
我已经读入了这样的文件缓冲区:
I have read in a file buffer like this:
let imageBuffer
try {
imageBuffer = fs.readFileSync('/some/path/to/image.jpg')
} catch (e) {
console.log('error reading in file', e)
}
然后我尝试stat
缓冲区:
let imageStats = fs.statSync(imageBuffer)
我收到以下错误:
Error: Path must be a string without null bytes
但是当我查看文档时,它说statSync
接受Buffer
:
But when I check the documentation it says that statSync
accepts a Buffer
:
path: string | Buffer | URL
我再次检查了Buffer实际上是一个Buffer:
And I double checked that the Buffer is in fact a Buffer:
console.log(imageBuffer instanceof Buffer) // returns true
还检查了尺寸:
console.log(imageBuffer.byteLength) // returns 5928109 which is the correct size
那么我在这里误解了什么?您只能stat
一个文件路径吗?该错误使它听起来像这样.但是文档似乎清楚地表明您也可以提供Buffer.
So what am I misunderstanding here? Can you only stat
a file path? The error makes it sound this way. But the documentation seems to make it clear that you can provide a Buffer too.
还是我误会了什么?
推荐答案
我认为 fs.statSync(path)
不明确.我相信这是说它想要一个路径.路径可以是<string> | <Buffer> | <URL>
,但是它必须是路径.
I think the documentation for fs.statSync(path)
is ambiguous. I believe it is saying that it wants a path. The path can be <string> | <Buffer> | <URL>
, but it needs to be a path.
因此,不要为它提供整个文件的缓冲区,而应为它提供一个缓冲区,如果将其转回字符串,则该缓冲区就是文件的路径.
So don't give it the buffer of the whole file, you give it a buffer that, if turned back into a string, is the path to the file.
换句话说,
-
fs.statSync("C:/foo.txt");
-
fs.statSync(Buffer.from("C:/foo.txt"));
-
fs.statSync(new URL("/foo", "https://www.example.com");
fs.statSync("C:/foo.txt");
fs.statSync(Buffer.from("C:/foo.txt"));
fs.statSync(new URL("/foo", "https://www.example.com");
考虑一下,这也是有道理的.操作系统如何为您提供有关文件原始字节的文件系统信息?一旦为字节,它将丢失文件系统的上下文.如果读入两个相同文件的内容,则它们的缓冲区将是相同的,但是任何一个的stat
都将为您提供不同的结果.您要stat
路径,而不是内容.
If you think about it, it makes sense too. How would an operating system be able to give you file system information about a a file's raw bytes? Once it's bytes, it loses the context of the file system. If you read in the contents of 2 identical files, their Buffers would be the same, yet the stat
of either would give you different results. You want to stat
a path, not contents.
这篇关于带有缓冲区"fs.statSync"“错误:路径必须是不包含空字节的字符串"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!