Skip to content

Asynchronous

jollen chen edited this page Apr 25, 2018 · 2 revisions

非同步處理

  • Callback (Lambda)
  • denodeify
  • Promise
  • await / async (ES2016)

Sample: Promise

'use strict';
 
var args = process.argv;
var hexs = [];

/*
 * Parse argv
 */
var filename = args[2];

for (var i = 3; i < args.length; i++) {
  var dec = parseInt( args[i] );
  var hex = dec.toString( 16 );
  hexs.push( hex );
}

/*
 * Main
 */
const denodeify = require('denodeify');

const fsOpen = denodeify(require('fs').open);
const fsRead = denodeify(require('fs').read);
const fsWrite = denodeify(require('fs').write);
const fsClose = denodeify(require('fs').close);
const fsFstat = denodeify(require('fs').fstat);

/*
 * Class
 */

class BinaryFile {
  constructor (path, mode, littleEndian) {
    littleEndian = littleEndian || false;
    this.path = path;
    this.mode = mode;
    this.endianness = littleEndian ? 'LE' : 'BE';
    this.cursor = 0;
  }

  open () {
    return new Promise((resolve) => {
      fsOpen(this.path, this.mode).then((fd) => {
        this.fd = fd;
        resolve();
      });
    });
  }

  seek (position) {
    this.cursor = position;
    return position;
  }

  read (length, position) {
    return new Promise((resolve) => {
      const buffer = new Buffer(length);
      fsRead(this.fd, buffer, 0, buffer.length, position || this.cursor).then((bytesRead) => {
        if (typeof position === 'undefined') this.cursor += bytesRead;
        resolve(buffer);
      });
    });
  }

  write (buffer, position) {
    return new Promise((resolve) => {
      fsWrite(this.fd, buffer, 0, buffer.length, position || this.cursor).then((bytesWritten) => {
        if (typeof position === 'undefined') this.cursor += bytesWritten;
        resolve(bytesWritten);
      });
    });
  }

  close () {
    return new Promise((resolve) => {
      fsClose(this.fd, () => {
        resolve();
      });
    });
  }  

  size () {
    return new Promise((resolve) => {
      fsFstat(this.fd).then((stat) => {
        resolve(stat.size);
      });
    });
  }  
}

/*
 * Main
 */
const myBinaryFile = new BinaryFile(filename, 'r');

myBinaryFile.open()

.then(function () {
	console.log('File opened');
	return myBinaryFile.size();

}).then(function(size) {
	console.log(`Size: ${size}`);
	return myBinaryFile.read(size);	

}).then(function (data) {
	var buf = [];

	for (i = 0; i < data.length; i++) {
		buf.push( parseInt(data[i]).toString(16) );
	}
	console.log( buf.join(' ') );

	return myBinaryFile.close();

}).then(function () {
	console.log('File closed');

}).catch(function (err) {
	console.log(`There was an error: ${err}`);
});

Clone this wiki locally