Promise Encapsulation Node read-write function __node

Source: Internet
Author: User

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);
  })
;




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.