[英]TypeError: fs.createWriteStream is not a function in Node
I couldn't find any resources online explaining why I'm running into this issue, even the official Node JS docs / API reference say that createWriteStream is a method in fs:我在网上找不到任何资源来解释为什么我会遇到这个问题,甚至官方的 Node JS 文档/API 参考资料都说 createWriteStream 是 fs 中的一个方法:
fs.createWriteStream(path[, options])[src]# fs.createWriteStream(path[, options])[src]#
All other stack overflow questions I found were people who were accidentally trying to access fs from the browser.我发现的所有其他堆栈溢出问题都是不小心尝试从浏览器访问 fs 的人。 So just to clarify, I am using Node!!所以澄清一下,我正在使用 Node!!
Example Code:示例代码:
import fs from 'fs/promises'
let ws = fs.createWriteStream("example.png")
Example code output:示例代码 output:
file:///workspace/buz/src/error.js:3
let ws = fs.createWriteStream("example.png")
^
TypeError: fs.createWriteStream is not a function
at file:///workspace/buz/src/error.js:3:13
at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
at async loadESM (node:internal/process/esm_loader:88:5)
at async handleMainPromise (node:internal/modules/run_main:61:12)
Node version: v16.15.1节点版本: v16.15.1
OS: Mac OS操作系统:苹果操作系统
I figured it out:我想到了:
createWriteStream()
is a function of fs , but not of fs/promises !! createWriteStream()
是fs的函数,但不是fs/promises的函数!
I couldn't find ANY documentation online for how to use createWriteStream()
with fs promises, so the easiest option is just to import it from the normal callback based fs:我在网上找不到任何关于如何使用带有 fs 承诺的createWriteStream()
的文档,所以最简单的选择就是从基于普通回调的 fs 中导入它:
import fs from 'fs/promises'
import {createWriteStream} from 'fs'
let ws = fs.createWriteStream("example.png")
I read through the Node documentation on fs
and went through all the methods in the the fs/promises
API and none of them return a <WriteStream>
.我通读了关于fs
的 Node 文档并浏览了fs/promises
API 中的所有方法,但没有一个返回<WriteStream>
。 So as of today, it seems like there's no way to get around this issue without importing stuff from the normal fs
API.所以到今天为止,如果不从普通的fs
API 导入东西,似乎没有办法解决这个问题。
Update: Changed wording to not use the word synchronous when describing the callback based fs API更新:在描述基于回调的 fs API 时,将措辞更改为不使用同步一词
if you want use fs/promise.如果你想使用 fs/promise。 First, you should open file to get a FileHandle.首先,您应该打开文件以获得 FileHandle。 then you can use fileHanlde.createWriteStream().那么你可以使用 fileHanlde.createWriteStream()。
import fs from 'fs/promises'
let file;
try{
file = await fs.open("example.png");
let ws = file.createWriteStream();
} finally(){
await file?.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.