all files / dir-compare/ fileDescriptorQueue.js

100% Statements 25/25
100% Branches 4/4
83.33% Functions 5/6
100% Lines 25/25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57                                      16×                          
'use strict';
 
var fs = require('fs');
var Promise = require('bluebird');
var util = require('util');
 
var log = function(str){
//	console.log(str);
}
/**
 * maxFilesNo - number of files that can be open concurrently.
 */
var FileQueue = function(maxFilesNo) {
	var activeJobs = {};
	var pendingJobs = [];
	var activeCount = 0;
 
	var open = function(path, flags, callback) {
		
//		log(util.format('a1: %s', i));
		pendingJobs.push({
			path : path,
			flags : flags,
			callback : callback
		});
		process();
	}
 
	var process = function() {
//		log(util.format('b1: %s', i));
//		log(util.format('b1_pending jobs:%d %s', pendingJobs.length, i));
		if (pendingJobs.length > 0 && activeCount < maxFilesNo) {
//			log(util.format('b2: %s', i));
			var job = pendingJobs.shift();
			activeJobs[job.fd] = job;
			activeCount++;
			fs.open(job.path, job.flags, function(err, fd) {
				job.callback(err, fd);
			});
		}
	}
 
	var close = function(fd, callback) {
//		log(util.format('c1: %s', i));
		delete activeJobs.fd;
		activeCount--;
		fs.close(fd, callback);
		process();
	}
 
	return {
		open : open,
		close : close
	};
}
 
module.exports = FileQueue;