admin管理员组文章数量:1414628
I'm encountering an issue with Node.js fs.writeFile
when trying to write to a file using a relative path (./message.txt
). Whenever I use ./
, I get the error:
[Error: EBADF: bad file descriptor, write] {
errno: -4083,
code: 'EBADF',
syscall: 'write'
}
However, if I use /message.txt
, the file gets created in the root of my C drive (C:\message.txt
) without any issues. I'm using Node.js v22.14.0, and this problem persists even after ensuring the directory exists and using absolute paths. I suspect it could be related to Node.js handling of relative paths in this version. Has anyone else experienced this, or is there a workaround to reliably write files using a relative path?
What I Tried & Expected Behavior
- Reinstalling Node.js – Issue persists in v22.14.0.
- Using an absolute path (
C:/Users/niran/Documents/message.txt
) – Works fine. - Using
path.join(__dirname, "message.txt")
– Still throwsEBADF
error. - Ensuring the directory exists before writing – No change.
- Running the script as an administrator – No effect.
Here’s my latest attempt:
try {
const fs = require("fs");
const path = require("path");
const filePath = path.join(__dirname, "message.txt");
console.log(filePath);
fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
fs.writeFile(filePath, "Hello, Node.js", (err) => {
if (err) {
console.error(err);
return;
}
console.log("The file has been saved!");
});
} catch (error) {
console.log(error);
}
What I Expected
I expected the file to be created in the same directory as my script, but instead, it throws EBADF
.
本文标签:
版权声明:本文标题:javascript - Why does `fs.writeFile` give "EBADF: bad file descriptor" when using `.`, but works with `` in No 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745156191a2645186.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论