The most recent way to implement mock virtual data through node is to use the FS module of node to read and write to our local files to achieve a mock function:
We can develop a JS file that specializes in encapsulating a simple file-reading function.
The JS code is as follows:
Let FS = require (' FS '); Let DEALFN = {/** * [write Data via promise] * @param {String} file [FileName] * @param {object} obj [written data (object)] * @return {Object}
[Promise Object] * * Writefiledata: (filename, obj) => {Let promise = new Promise ((Resolve, reject) => {
obj = json.stringify (obj);
Fs.writefile ("./data/" + filename, obj, function (err) {if (err) {Reject ("fail" + Err)
else {Resolve ("write success!");
}
});
}) return promise; },/** * [read stored data through promise] * @param {String} file [FileName] * @return {object} [Promise objects]/readfiledata: (filename) => {Let promise = new promise (Resolve, Reject) => {fs.readfile ("./data/" + filename, "UT
F-8 ", (err, data) => {if (err) {Console.log (err);
Reject ("read Filedata error!"); }else {data = JSON. Parse (data);
Resolve (data);
}
})
});
return promise;
}
}; Module.exports = Datafn;
Next we can call the following:
Router.post ('/test.json ', function (req,res,next) {let
senddata = {message
: ' OK ',
data: {}
};
Dealfn.readfiledata ('.. /data/test.json '). Then (data=>{
senddata.data = data;
Res.status. JSON (SendData);
}). catch (message=>{
senddata.errno =-1;
Senddata.message = ' temporarily no data ';
Res.status. JSON (SendData);
})
;