gpt4 book ai didi

node.js - 不回调 Node js 写入文件

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:42 25 4
gpt4 key购买 nike

如何编写没有回调的 writeFile() 函数?

这不起作用:

fs.writeFile("/logs/file.log", 'Message')

fs.writeFile("/logs/file.log", 'Message',null)

两者都抛出:

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function

我需要实现一个非阻塞解决方案。

最佳答案

// create a noop - as in "no operation"
const noop = () => {};

// and pass that in
fs.writeFile("filename.txt", "content", noop);

如果您对必须传递回调感到烦恼,请创建另一个函数:

const writeFile = (filename, content) => {fs.writeFile(filename, content, () => {}));

// and use it like this
writeFile("filename.txt", "content");

更好的是,如果您使用的是 NodeJS > v10.0,则使用 fs.promises.writeFile API:

import fs from "fs";

// this returns a Promise
fs.promises.writeFile("filename.txt", "content");

// which you can await in an async function
async main() {
try {
await fs.promises.writeFile("filename.txt", "content");
}
catch (e) {
console.error(e);
}
}

// or .then and .catch on it.
fs.promises.writeFile("filename.txt", "content")
.then(() => { /* do something after */ })
.catch(e => console.error(e));

如果在 Node < v10.0 上,您可以使用 promisify 实用程序:

import { promisify } from "util";
import fs from "fs";

const writeFile = promisify(fs.writeFile);

// this returns a Promise that you can await or .then
await writeFile("filename.txt", "content");

关于node.js - 不回调 Node js 写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55767491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com