我在我的程序中得到了错误Uncaught TypeError: fs.writeFile is not a function,其中我只想写一些东西到一个JSON文件中。fs.readFileSync函数正常工作,但由于某种原因,fs.writeFile没有工作。这是我的代码:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Hello World!</h1>
<button id="button">Write Something</button>
<script src="./app.js"></script>
</body>
</html>JavaScript:
const fs = require("fs");
const data = fs.readFileSync("db.json", "utf8");
const db = JSON.parse(data);
console.log(db);
document.getElementById("button").onclick = () => {
fs.writeFile("db.json", "test", () => {
console.log("Written file!");
});
};杰森:
["something1", "something2"]为了让你知道,我在用包裹作为我的打包机。请帮我解释一下为什么这不起作用。
发布于 2021-05-31 10:19:42
发布于 2021-05-31 10:17:49
您将无法在浏览器中使用writeFile,即使您使用了绑定器,因为这是Node.js而不是browser API。绑定器不会在浏览器的构建中嵌入本机Node.js函数,因为这是两个不同的执行环境。
在浏览器中,您不能在未经用户同意的情况下任意触发磁盘上的文件写入,因此您必须实际触发一个文件下载。
https://stackoverflow.com/questions/67771853
复制相似问题