UNPKG

castor-load

Version:

Traverse a directory to build a MongoDB collection with the found files. Then it's enable to keep directory and collection synchronised.

89 lines (73 loc) 2.07 kB
'use strict'; var path = require('path') , basename = path.basename(__filename, '.js') , debug = require('debug')('castor:load:' + basename) , util = require('util') , assert = require('assert') , crypto = require('crypto') , fs = require('fs') , extend = require('extend') ; function File(pathname, stats, startobj) { if (!(this instanceof File)) { return new File(pathname, stats); } var self = this; assert.equal(typeof pathname, 'string'); stats = stats || {} var type; if (typeof(stats.isFile) === "function") { if (stats.isFile()) { type = 'file'; } else if (stats.isDirectory()) { type = 'directory'; } else { type = 'misc'; } } self.doc = {}; if (startobj) { extend(self.doc, startobj) } self.doc.filetype = type || 'unknown'; self.doc.basedir = startobj.basedir || ''; self.doc.fid = crypto.createHash('sha1').update(pathname).digest('hex'); self.doc.location = pathname; self.doc.basename = path.basename(pathname); self.doc.filename = pathname.replace(self.doc.basedir, ''); self.doc.directory = path.dirname(pathname).replace(self.doc.basedir, ''); self.doc.extension = path.extname(pathname).replace('.', ''); self.doc.filesize = stats.size || 0; self.doc.dateCreated = stats.ctime || null; self.doc.dateModified = stats.mtime || null; self.doc.dateAccessed = stats.atime || null; self.doc.sha1 = undefined; } File.prototype.analyze = function (fn) { var self = this; if (self.doc.sha1 || self.doc.filetype !== 'file') { return fn(null, self.doc); } var s = fs.ReadStream(self.doc.location) , shasum = crypto.createHash('sha1'); s.on('data', function(d) { shasum.update(d); }); s.on('end', function() { self.doc.sha1 = shasum.digest('hex'); fn(null, self.doc) }); s.on('error', function(e) { fn(e, self.doc); // fn(new Error('Analyse failed')); }); return s; } File.prototype.get = function () { var self = this; return self.doc; } module.exports = File;