UNPKG

2.5 kBJavaScriptView Raw
1'use strict';
2
3const util = require('util');
4
5const Item = require('./item');
6
7const EMPTY = Buffer.alloc(0);
8const constants = require('constants');
9
10/**
11 * A file.
12 * @constructor
13 */
14function File() {
15 Item.call(this);
16
17 /**
18 * File content.
19 * @type {Buffer}
20 */
21 this._content = EMPTY;
22}
23util.inherits(File, Item);
24
25/**
26 * Get the file contents.
27 * @return {Buffer} File contents.
28 */
29File.prototype.getContent = function() {
30 this.setATime(new Date());
31 return this._content;
32};
33
34/**
35 * Set the file contents.
36 * @param {string|Buffer} content File contents.
37 */
38File.prototype.setContent = function(content) {
39 if (typeof content === 'string') {
40 content = Buffer.from(content);
41 } else if (!Buffer.isBuffer(content)) {
42 throw new Error('File content must be a string or buffer');
43 }
44 this._content = content;
45 const now = Date.now();
46 this.setCTime(new Date(now));
47 this.setMTime(new Date(now));
48};
49
50/**
51 * Get file stats.
52 * @return {Object} Stats properties.
53 */
54File.prototype.getStats = function(bigint) {
55 const size = this._content.length;
56 const stats = Item.prototype.getStats.call(this, bigint);
57 const convert = bigint ? v => BigInt(v) : v => v;
58
59 stats[1] = convert(this.getMode() | constants.S_IFREG); // mode
60 stats[8] = convert(size); // size
61 stats[9] = convert(Math.ceil(size / 512)); // blocks
62
63 return stats;
64};
65
66/**
67 * Export the constructor.
68 * @type {function()}
69 */
70exports = module.exports = File;
71
72/**
73 * Standard input.
74 * @constructor
75 */
76function StandardInput() {
77 File.call(this);
78 this.setMode(438); // 0666
79}
80util.inherits(StandardInput, File);
81
82exports.StandardInput = StandardInput;
83
84/**
85 * Standard output.
86 * @constructor
87 */
88function StandardOutput() {
89 File.call(this);
90 this.setMode(438); // 0666
91}
92util.inherits(StandardOutput, File);
93
94/**
95 * Write the contents to stdout.
96 * @param {string|Buffer} content File contents.
97 */
98StandardOutput.prototype.setContent = function(content) {
99 if (process.stdout.isTTY) {
100 process.stdout.write(content);
101 }
102};
103
104exports.StandardOutput = StandardOutput;
105
106/**
107 * Standard error.
108 * @constructor
109 */
110function StandardError() {
111 File.call(this);
112 this.setMode(438); // 0666
113}
114util.inherits(StandardError, File);
115
116/**
117 * Write the contents to stderr.
118 * @param {string|Buffer} content File contents.
119 */
120StandardError.prototype.setContent = function(content) {
121 if (process.stderr.isTTY) {
122 process.stderr.write(content);
123 }
124};
125
126exports.StandardError = StandardError;