Encapsulate ReadFile as a method (to solve asynchronous Problems)
Cause: because Node. JS is non-blocking i/o, It is asynchronous, the read file is an I/O request, so it is thrown, and all NON-I/O requests are completed before they are made
Code with Async problem:
var fs = require ("fs"); function fnreadfile (file) { function(err, data) { return data; }); Console.log (fnreadfile ("hei.txt")); //output undefined cause the Fs.readfile method is asynchronous
Workaround One: Callback function
var fs = require ("fs"); function fnreadfile (file, callback) { function(err, data) { callback (data.tostring ()); });} Fnreadfile (function(res) { console.log ("read data is:" + res);});
Method Two: Events module monitoring on broadcast emit
var events = Require ("events"); var fs = require ("fs"); var New Events (); Myevent.on (function(str) { console.log ("read data:" + str);}); function fnreadfile (file) { function(err, data) { myevent.emit ("showData", (data); }); Fnreadfile ("hei.txt");
Node. JS in the Events module application