UNPKG

2.4 kBJavaScriptView Raw
1'use strict';
2
3const util = require('util');
4
5const Item = require('./item');
6
7const constants = require('constants');
8
9/**
10 * A directory.
11 * @constructor
12 */
13function Directory() {
14 Item.call(this);
15
16 /**
17 * Items in this directory.
18 * @type {Object.<string, Item>}
19 */
20 this._items = {};
21
22 /**
23 * Permissions.
24 */
25 this._mode = 511; // 0777
26}
27util.inherits(Directory, Item);
28
29/**
30 * Add an item to the directory.
31 * @param {string} name The name to give the item.
32 * @param {Item} item The item to add.
33 * @return {Item} The added item.
34 */
35Directory.prototype.addItem = function(name, item) {
36 if (this._items.hasOwnProperty(name)) {
37 throw new Error('Item with the same name already exists: ' + name);
38 }
39 this._items[name] = item;
40 ++item.links;
41 if (item instanceof Directory) {
42 // for '.' entry
43 ++item.links;
44 // for subdirectory
45 ++this.links;
46 }
47 this.setMTime(new Date());
48 return item;
49};
50
51/**
52 * Get a named item.
53 * @param {string} name Item name.
54 * @return {Item} The named item (or null if none).
55 */
56Directory.prototype.getItem = function(name) {
57 let item = null;
58 if (this._items.hasOwnProperty(name)) {
59 item = this._items[name];
60 }
61 return item;
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 const 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 * Get list of item names in this directory.
88 * @return {Array.<string>} Item names.
89 */
90Directory.prototype.list = function() {
91 return Object.keys(this._items).sort();
92};
93
94/**
95 * Get directory stats.
96 * @return {Object} Stats properties.
97 */
98Directory.prototype.getStats = function(bigint) {
99 const stats = Item.prototype.getStats.call(this, bigint);
100 const convert = bigint ? v => BigInt(v) : v => v;
101
102 stats[1] = convert(this.getMode() | constants.S_IFDIR); // mode
103 stats[8] = convert(1); // size
104 stats[9] = convert(1); // blocks
105
106 return stats;
107};
108
109/**
110 * Export the constructor.
111 * @type {function()}
112 */
113exports = module.exports = Directory;