1

Could someone please explain me the node.js ReadFile() function syntax? I don't understand why function(err,data) falls inside it. I'm totally new to programming. The example on node.js website is still confusing. thanks!

sample code from node.js website

fs.readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});
Ranga RS
  • 142
  • 9
  • 1
    what is the error it throws? and more generally, what you don't understand - the syntax? why it works/fails? – arieljannai May 08 '17 at 11:37
  • please learn JS first... have a look at *arrow functions*, *asynchronous callbacks*, and *how to return from an asynchronous call?* – Jonas Wilms May 08 '17 at 11:38
  • 2
    Possible duplicate of [How to return value from an asynchronous callback function?](http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Jonas Wilms May 08 '17 at 11:39
  • I'm a UI designer in a product company and we design UI for different features and minor upgrades. we then host it on a local server and share it with the concern developers. It has become clumsy now as we have a lot of projects in it and it's quite hard to find the right files. We thought of building a simple index.html file which will be accessed locally by anyone. I have a JSON file which contains the info abt the projects, used AJAX to dynamically build UI with JSON data, now I wanna add an "add task" btn which will add new task form data in JSON file. what is the best practice to follow? – Ranga RS May 09 '17 at 06:13

2 Answers2

1

ReadFile method reads the file that is define in the first parameter. When it's over then will execute the passed function or callback (second parameter). This function has two input parameter error and data. If an error is not ocurred then error will be undefined and data will contain file data.

ChaosPattern
  • 124
  • 5
1

Study about Asynchronous Callbacks in JavaScript. In your question

fs.readfile('xyz',(err,data)=>{});

What it does is, it creates a non-blocking execution call, which means that the program does not wait for the file to be read completely. The program execution ends and when the file has been read the output is logged. For a basic understanding of the scenario you can visit: https://www.tutorialspoint.com/nodejs/nodejs_callbacks_concept.htm

Bhushan K
  • 29
  • 5