The asynchronous mechanism of node. JS is implemented by events and callback functions, and it may feel like a violation of the routine at first, but the habit will find it simple.
However, there are a lot of traps in this, a very easy problem is to return to the loop callback function.
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 operation are as follows:
[' A.txt ', ' b.txt ', ' c.txt ']3undefined[' a.txt ', ' b.txt ', ' c.txt ']3undefined[' a.txt ', ' b.txt ', ' c.txt ']3undefined
Here's how to fix it:
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