The asynchronous mechanism of Node. JS is implemented by events and callback functions, which may feel like a violation of the routine, but the habit will find it very easy to get Started.
There are, however, many pitfalls in This. A very easy problem to encounter is to go back to the callback function of the Loop.
eq
var fs=require (' FS '); var files=[' a.txt ', ' b.txt ', ' c.txt '];for (var i=0;i<files.length;i++) { fs.readfile (file [i], ' utf-8 ', function (err,contents) { console.log (files); Console.log (i); Console.log (files[i]);} )}
The results of the actual execution are as Follows:
[' a.txt ', ' b.txt ', ' c.txt ']3undefined[' a.txt ', ' b.txt ', ' c.txt ']3undefined[' a.txt ', ' b.txt ', ' c.txt ']3undefined
The workaround is as Follows:
var fs=require (' FS '); var files=[' a.txt ', ' b.txt ', ' c.txt '];files.foreach (function (filename) {fs.readfile (filename, ' Utf-8 ', function (err,contents) {console.log (filename+ ":" +contents); })})
Cyclic traps in the Nodejs