UNPKG

2.25 kBJavaScriptView Raw
1var path = require('path');
2var util = require('util');
3
4var Item = require('./item');
5
6var constants = process.binding('constants');
7
8
9
10/**
11 * A directory.
12 * @constructor
13 */
14function Directory() {
15 Item.call(this);
16
17 /**
18 * Items in this directory.
19 * @type {Object.<string, Item>}
20 */
21 this._items = {};
22
23}
24util.inherits(Directory, Item);
25
26
27/**
28 * Add an item to the directory.
29 * @param {string} name The name to give the item.
30 * @param {Item} item The item to add.
31 * @return {Item} The added item.
32 */
33Directory.prototype.addItem = function(name, item) {
34 if (this._items.hasOwnProperty(name)) {
35 throw new Error('Item with the same name already exists: ' + name);
36 }
37 this._items[name] = item;
38 ++item.links;
39 if (item instanceof Directory) {
40 // for '.' entry
41 ++item.links;
42 // for subdirectory
43 ++this.links;
44 }
45 this.setMTime(new Date());
46 return item;
47};
48
49
50/**
51 * Get a named item.
52 * @param {string} name Item name.
53 * @return {Item} The named item (or null if none).
54 */
55Directory.prototype.getItem = function(name) {
56 var item = null;
57 if (this._items.hasOwnProperty(name)) {
58 item = this._items[name];
59 }
60 return item;
61};
62
63
64/**
65 * Remove an item.
66 * @param {string} name Name of item to remove.
67 * @return {Item} The orphan item.
68 */
69Directory.prototype.removeItem = function(name) {
70 if (!this._items.hasOwnProperty(name)) {
71 throw new Error('Item does not exist in directory: ' + name);
72 }
73 var item = this._items[name];
74 delete this._items[name];
75 --item.links;
76 if (item instanceof Directory) {
77 // for '.' entry
78 --item.links;
79 // for subdirectory
80 --this.links;
81 }
82 this.setMTime(new Date());
83 return item;
84};
85
86
87/**
88 * Get list of item names in this directory.
89 * @return {Array.<string>} Item names.
90 */
91Directory.prototype.list = function() {
92 return Object.keys(this._items).sort();
93};
94
95
96/**
97 * Get directory stats.
98 * @return {Object} Stats properties.
99 */
100Directory.prototype.getStats = function() {
101 var stats = Item.prototype.getStats.call(this);
102 stats.mode = this.getMode() | constants.S_IFDIR;
103 stats.size = 1;
104 stats.blocks = 1;
105 return stats;
106};
107
108
109/**
110 * Export the constructor.
111 * @type {function()}
112 */
113exports = module.exports = Directory;