UNPKG

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