javascriptnode.jsdebuggingtypeerrornode.js-fs

Node.js returns TypeError when creating a file using fs.writeFile


I've just started learning Node.js. Right now I'm working on creating new files and directories methods.

This is my code:

var fs = require('fs');


fs.mkdir("stuff", function () {
    fs.readFile('readMe.txt', 'utf8', function (err, data){
        fs.writeFile('./stuff/writeMe.txt', data);
    });
});

It does create the directory and does read the file, but doesn't create a new file. I'm getting this error:

fs.js:152
  throw new ERR_INVALID_CALLBACK(cb);
  ^

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
[90m    at maybeCallback (fs.js:152:9)[39m
[90m    at Object.writeFile (fs.js:1351:14)[39m
    at D:\PRANAV\Learning Folder\Node\app.js:6:12
[90m    at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3)[39m {
  code: [32m'ERR_INVALID_CALLBACK'[39m
}

Solution

  • fs.writeFile's last argument should be a callback function. Right now, you're missing it:

    fs.mkdir("stuff", function () {
        fs.readFile('readMe.txt', 'utf8', function (err, data) {
            fs.writeFile('./stuff/writeMe.txt', data, function (err) {
                if (err) {
                    throw err;
                }
                console.log('written successfully!');
            });
        });
    });