laura
laura

Reputation: 31

Error trying to use writeFile with NodeJS

I am trying to write a function using fs.writeFile but I am getting this error.

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined

I am not so familiar with JS so I'd appreciate the help.

My function:

write(fileName, cb) {
fs.writeFile(fileName, function(succ, err) {
  if (err) {
    cb(err);
  } else {
    cb(succ);
  }
});

}

And this function is being called by this:

// write string version to file, starting at root element
root.write('test.svg', () => console.log('done writing!'));

This last code is correct (it was a test provided by the instructor).

Upvotes: 1

Views: 805

Answers (1)

about14sheep
about14sheep

Reputation: 1999

The fs module writeFile, from the fs callback api, takes in three parameters. First being the name of the file, the second is the data to write, and third is a callback for when the write is finished:

fs.writeFile('message.txt', data, (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
});

Since you are only passing in two parameters the callback is undefined, as the error states.

also, the callback does not take in two parameters

read more about fs.writeFile

Upvotes: 1

Related Questions