skip to Main Content

`

const fs = require('fs');

fs.readFile("datafile.txt", "utf-8", function(err, data){
    let newData = "Some string to write in file";

    fs.writeFile("datafile.txt",  newData, (err) => { 
        if (err) 
          console.log(err); 
        else { 
          console.log("File written successfullyn"); 
          console.log(fs.readFile("datafile.txt", "utf-8")); 
        } 
      }); 
})

`

The data has been written successfully but having this error on line with fs.readFile() at the end.
Can anyone help me figure it out?
Thanks.

Complete error

node file.js

File written successfully

node:internal/validators:455
    throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received type string ('utf-8')
    at maybeCallback (node:fs:178:3)
    at Object.readFile (node:fs:369:14)
    at D:file.js:16:26
    at FSReqCallback.oncomplete (node:fs:189:23) {
  code: 'ERR_INVALID_ARG_TYPE'
}

Node.js v20.10.0

I am probably expecting some issue with async file but still not sure how to solve it.

2

Answers


  1. The error message you received indicates that there is an issue with the argument type being passed to a function in your code. Specifically, the error points to the use of the readFile function from the Node.js fs module.

    The readFile function expects the second argument to be a callback function, but in your code, it appears to be a string (‘utf-8’) instead. To resolve this error, you need to provide a valid callback function as the second argument to readFile.

    Here’s an example of how to use readFile correctly:

    const fs = require('fs');
    
    fs.readFile('path/to/file.txt', 'utf-8', (err, data) => {
      if (err) {
        console.error(err);
        return;
      }
      // Do something with the file data
      console.log(data);
    });
    

    In this example, the second argument to readFile is the encoding (‘utf-8’), and the third argument is the callback function that will be executed when the file is read. The callback function takes two parameters, err and data, and you can handle any errors or process the file data within the callback.

    Login or Signup to reply.
  2. fs.readFile takes 3 or 2(if encoding is not passed) arguments,

    1. filename <- required
    2. encoding <- optional
    3. callback <- required

    data read from readFile will be passed to this callback function

    fs.readFile("datafile.txt", "utf-8", (error, data) => {
    if(error){
    throw new Error('File Read Error');
    }
    console.log(data);
    })
    

    Please do proper research and read docs before jumping into stackoverflow.
    Good Luck!
    https://www.geeksforgeeks.org/node-js-file-system/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search