Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to file without callback Node js

Tags:

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)

Both throw a:

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function

I need to implement a non-blocking solution.

like image 799
caravana_942 Avatar asked Apr 19 '19 20:04

caravana_942


People also ask

What is the reason to choose fs readFile () method to read a file in node JS?

Reading file Asynchronously Reading a file asynchronously is the simplest way to read the file using fs. readFile() function. It is non-blocking because it doesn't block the rest of the code while executing. As you know, basic JavaScript functions and this asynchronous function are features of JavaScript.

What is writeFileSync in node JS?

writeFileSync() to write data in files. The latter is a synchronous method for writing data in files. fs. writeFileSync() is a synchronous method, and synchronous code blocks the execution of program. Hence, it is preferred and good practice to use asynchronous methods in Node.

Is fs writeFile async?

writeFile() is an asynchronous method for writing data in files of any type.

Is fs Async readFile?

The fs. readFile() method lets you asynchronously read the entire contents of a file.


4 Answers

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

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

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");

Better yet, if you're using NodeJS > v10.0, then use the 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));

If on Node < v10.0 you can use the promisify utility:

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");
like image 54
Arash Motamedi Avatar answered Oct 18 '22 00:10

Arash Motamedi


I need to implement a non-blocking solution.

Because of that you must use an ASYNC function instead of sync.

writefile() is an async function, thus you need a callback function for it.

var fs = require('fs');
fs.writeFile("/logs/file.log", "Message", function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file is saved!");
    // Here you can write code about what happen next!

}); 
like image 4
Benjamin Avatar answered Oct 18 '22 01:10

Benjamin


If you really don't care about the result (error yes/no), this might do the trick.

fs.writeFile("/logs/file.log", 'Message', () => {})
like image 3
Etienne Cha Avatar answered Oct 18 '22 00:10

Etienne Cha


Instead of using writeFile, you can use writeFileSync instead. writeFile requires the callback to be passed whereas writeFileSync doesn't need a callback function. For more info, you can refer to writeFileSync NodeJS Docs

This should work for you

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

As I read your comment on the question, if you are looking to stick to writeFile, you need to pass the callback function as it's async. You can shorten it by writing

fs.writeFile("/logs/file.log", 'Message', () => {})
like image 1
Mr. Alien Avatar answered Oct 18 '22 00:10

Mr. Alien