mzee
mzee

Reputation: 125

"'cb' argument must be of type function" error, invoking fs.writeFile()

I wrote this code:

var fs = require('fs');

var data = {
    name:'Bob'
}

and I get this error:

fs.writeFile('data.json',data) "the 'cb' argument must be of type function. Received undefined"

How do I fix it?

Upvotes: 10

Views: 51871

Answers (1)

AKX
AKX

Reputation: 169268

You're using the asynchronous callback-style fs.writeFile API without a callback (cb for short).

In addition, you're not encoding your data to JSON before attempting to write it, so that too would fail.

Either:

  • use fs.writeFileSync() for synchronous file writing:
    fs.writeFileSync("data.json", JSON.stringify(data));
    
  • pass in a callback (that can be anything, but it needs to be there):
    fs.writeFile("data.json", JSON.stringify(data), (err) => err && console.error(err));
    
  • use fs/promises's promise-based asynchronous API:
    var fsp = require('fs/promises');
    await fsp.writeFile("data.json", JSON.stringify(data));
    

Upvotes: 30

Related Questions