Write to file without callback Node js

car*_*942 1 node.js

How do you write a writeFile() function without a callback?

This does not work:

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

fs.writeFile("/logs/file.log", 'Message',null)
Run Code Online (Sandbox Code Playgroud)

Both throw a:

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
Run Code Online (Sandbox Code Playgroud)

I need to implement a non-blocking solution.

Ara*_*edi 5

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

// and pass that in
fs.writeFile("filename.txt", "content", noop);
Run Code Online (Sandbox Code Playgroud)

If you're bothered by having to pass a callback at all, create another function:

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

// and use it like this
writeFile("filename.txt", "content");
Run Code Online (Sandbox Code Playgroud)

Better yet, promisify the function:

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

const writeFile = promisify(fs.writeFile);

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

// which you can put in a try/catch block (in an async method)
// or .then and .catch on it.
writeFile("filename2.txt", "content").then(() => { /* do something after */ });
Run Code Online (Sandbox Code Playgroud)