All files / lib/internal/fs streams.js

95.16% Statements 472/496
93.46% Branches 143/153
84% Functions 21/25
95.16% Lines 472/496

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 2343x 2343x 2343x 26x 26x 26x 2317x 2343x 8x 8x 8x 6x 4x 4x 4x 6x 2x 2x 2x     8x 8x 2320x 2309x 2309x 14x 2305x 2295x 2295x 2295x 2295x 2295x 2309x 2309x 2343x 110x 110x 110x 16x 16x   16x 16x 16x 16x 16x 16x 16x 17x 17x 17x 16x 16x 3x 3x 3x 16x 16x         16x 110x 110x 2315x 2315x 16x 2314x 2299x 2297x 2299x 2299x 2299x 2315x 110x 30x 30x 11x 11x 11x 11x 11x 11x 30x 19x 17x 17x 1x 1x 1x 16x 16x 16x 16x 16x 16x 2x 2x 2x 30x 110x 2304x 2304x 2304x 2300x 2300x 2300x 2300x 2302x 2295x 2295x 2295x 2295x 2295x 2296x 2270x 2270x 2270x 2270x 2270x 2270x 2270x 2270x 2270x 2270x 2302x 25x 25x 2291x 2292x 2304x 2304x 2304x 2304x 2304x 2282x 2282x 2289x 2289x 2289x 2289x 2289x 2289x 2289x 2300x 43x 43x 43x 43x 2279x 2279x 2294x 2261x 2297x 17x 17x 17x 3x 3x 3x 3x 3x 3x 17x 2270x 2270x 2304x 110x 110x 110x 110x 110x 110x 1x 110x 110x     110x 110x 110x 1x 110x 110x 110x 110x 110x 110x 14043x 14043x 14043x 14043x 14043x 7x 7x 7x 14036x 14036x 14036x 14036x 14036x 14036x 14036x 14036x 14036x 14036x 6x 6x 6x 14030x 14035x 3x 14035x 11919x 186x 186x 11919x 11919x 11919x 11919x 2107x 2107x 2107x 2107x 2107x 2107x 2107x 11919x 11919x 14027x 2108x 2108x 14036x 110x 110x 110x 2248x 2248x 2248x 2248x 2248x 2248x 2248x 6x 2243x 2242x 2242x 110x 110x 110x 67x 67x 110x 110x 110x 110x 110x 110x 110x 110x 92x 92x 92x 88x 88x 88x 88x 88x 88x 90x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 90x 5x 5x 80x 80x 92x 92x 92x 1x 1x 1x 79x 79x 79x 79x 79x 79x 78x 78x 78x 78x 76x 76x 77x 77x 88x     84x 1x 1x 77x 77x 77x 77x 77x 77x 84x 6x 6x 6x 6x 74x 74x 74x 74x 83x 92x 110x 110x 110x 110x 110x 110x 9x 110x 110x     110x 110x 110x 1x 110x 110x 110x 110x 110x 110x 3269x 3269x 3269x 3269x         3269x 3269x 1x 1x 3268x 3268x 3268x 3269x 3269x 3269x 3269x 110x 110x 110x 8x 8x 8x 8x 8x 36x 36x 36x 36x 36x 8x 8x 8x 8x 8x         8x 8x     8x 8x 8x 8x 8x 8x 8x 110x 110x 110x 67x 67x 67x 67x 67x 67x 67x   67x 67x 67x 110x 110x 110x 11x 7x 2x 2x 2x 5x 5x 9x 9x 9x 11x 2x 2x 9x 9x 9x 9x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x  
'use strict';
 
const {
  Array,
  FunctionPrototypeBind,
  MathMin,
  ObjectDefineProperty,
  ObjectSetPrototypeOf,
  PromisePrototypeThen,
  ReflectApply,
  Symbol,
} = primordials;
 
const {
  ERR_INVALID_ARG_TYPE,
  ERR_OUT_OF_RANGE,
  ERR_METHOD_NOT_IMPLEMENTED,
} = require('internal/errors').codes;
const {
  deprecate,
  kEmptyObject,
} = require('internal/util');
const {
  validateFunction,
  validateInteger,
} = require('internal/validators');
const { errorOrDestroy } = require('internal/streams/destroy');
const fs = require('fs');
const { kRef, kUnref, FileHandle } = require('internal/fs/promises');
const { Buffer } = require('buffer');
const {
  copyObject,
  getOptions,
  getValidatedFd,
  validatePath,
} = require('internal/fs/utils');
const { Readable, Writable, finished } = require('stream');
const { toPathIfFileURL } = require('internal/url');
const kIoDone = Symbol('kIoDone');
const kIsPerformingIO = Symbol('kIsPerformingIO');
 
const kFs = Symbol('kFs');
const kHandle = Symbol('kHandle');
 
function _construct(callback) {
  const stream = this;
  if (typeof stream.fd === 'number') {
    callback();
    return;
  }
 
  if (stream.open !== openWriteFs && stream.open !== openReadFs) {
    // Backwards compat for monkey patching open().
    const orgEmit = stream.emit;
    stream.emit = function(...args) {
      if (args[0] === 'open') {
        this.emit = orgEmit;
        callback();
        ReflectApply(orgEmit, this, args);
      } else if (args[0] === 'error') {
        this.emit = orgEmit;
        callback(args[1]);
      } else {
        ReflectApply(orgEmit, this, args);
      }
    };
    stream.open();
  } else {
    stream[kFs].open(stream.path, stream.flags, stream.mode, (er, fd) => {
      if (er) {
        callback(er);
      } else {
        stream.fd = fd;
        callback();
        stream.emit('open', stream.fd);
        stream.emit('ready');
      }
    });
  }
}
 
// This generates an fs operations structure for a FileHandle
const FileHandleOperations = (handle) => {
  return {
    open: (path, flags, mode, cb) => {
      throw new ERR_METHOD_NOT_IMPLEMENTED('open()');
    },
    close: (fd, cb) => {
      handle[kUnref]();
      PromisePrototypeThen(handle.close(),
                           () => cb(), cb);
    },
    read: (fd, buf, offset, length, pos, cb) => {
      PromisePrototypeThen(handle.read(buf, offset, length, pos),
                           (r) => cb(null, r.bytesRead, r.buffer),
                           (err) => cb(err, 0, buf));
    },
    write: (fd, buf, offset, length, pos, cb) => {
      PromisePrototypeThen(handle.write(buf, offset, length, pos),
                           (r) => cb(null, r.bytesWritten, r.buffer),
                           (err) => cb(err, 0, buf));
    },
    writev: (fd, buffers, pos, cb) => {
      PromisePrototypeThen(handle.writev(buffers, pos),
                           (r) => cb(null, r.bytesWritten, r.buffers),
                           (err) => cb(err, 0, buffers));
    }
  };
};
 
function close(stream, err, cb) {
  if (!stream.fd) {
    cb(err);
  } else {
    stream[kFs].close(stream.fd, (er) => {
      cb(er || err);
    });
    stream.fd = null;
  }
}
 
function importFd(stream, options) {
  if (typeof options.fd === 'number') {
    // When fd is a raw descriptor, we must keep our fingers crossed
    // that the descriptor won't get closed, or worse, replaced with
    // another one
    // https://github.com/nodejs/node/issues/35862
    stream[kFs] = options.fs || fs;
    return options.fd;
  } else if (typeof options.fd === 'object' &&
             options.fd instanceof FileHandle) {
    // When fd is a FileHandle we can listen for 'close' events
    if (options.fs) {
      // FileHandle is not supported with custom fs operations
      throw new ERR_METHOD_NOT_IMPLEMENTED('FileHandle with fs');
    }
    stream[kHandle] = options.fd;
    stream[kFs] = FileHandleOperations(stream[kHandle]);
    stream[kHandle][kRef]();
    options.fd.on('close', FunctionPrototypeBind(stream.close, stream));
    return options.fd.fd;
  }
 
  throw ERR_INVALID_ARG_TYPE('options.fd',
                             ['number', 'FileHandle'], options.fd);
}
 
function ReadStream(path, options) {
  if (!(this instanceof ReadStream))
    return new ReadStream(path, options);
 
  // A little bit bigger buffer and water marks by default
  options = copyObject(getOptions(options, kEmptyObject));
  if (options.highWaterMark === undefined)
    options.highWaterMark = 64 * 1024;
 
  if (options.autoDestroy === undefined) {
    options.autoDestroy = false;
  }
 
  if (options.fd == null) {
    this.fd = null;
    this[kFs] = options.fs || fs;
    validateFunction(this[kFs].open, 'options.fs.open');
 
    // Path will be ignored when fd is specified, so it can be falsy
    this.path = toPathIfFileURL(path);
    this.flags = options.flags === undefined ? 'r' : options.flags;
    this.mode = options.mode === undefined ? 0o666 : options.mode;
 
    validatePath(this.path);
  } else {
    this.fd = getValidatedFd(importFd(this, options));
  }
 
  options.autoDestroy = options.autoClose === undefined ?
    true : options.autoClose;
 
  validateFunction(this[kFs].read, 'options.fs.read');
 
  if (options.autoDestroy) {
    validateFunction(this[kFs].close, 'options.fs.close');
  }
 
  this.start = options.start;
  this.end = options.end;
  this.pos = undefined;
  this.bytesRead = 0;
  this[kIsPerformingIO] = false;
 
  if (this.start !== undefined) {
    validateInteger(this.start, 'start', 0);
 
    this.pos = this.start;
  }
 
 
  if (this.end === undefined) {
    this.end = Infinity;
  } else if (this.end !== Infinity) {
    validateInteger(this.end, 'end', 0);
 
    if (this.start !== undefined && this.start > this.end) {
      throw new ERR_OUT_OF_RANGE(
        'start',
        `<= "end" (here: ${this.end})`,
        this.start
      );
    }
  }
 
  ReflectApply(Readable, this, [options]);
}
ObjectSetPrototypeOf(ReadStream.prototype, Readable.prototype);
ObjectSetPrototypeOf(ReadStream, Readable);
 
ObjectDefineProperty(ReadStream.prototype, 'autoClose', {
  __proto__: null,
  get() {
    return this._readableState.autoDestroy;
  },
  set(val) {
    this._readableState.autoDestroy = val;
  }
});
 
const openReadFs = deprecate(function() {
  // Noop.
}, 'ReadStream.prototype.open() is deprecated', 'DEP0135');
ReadStream.prototype.open = openReadFs;
 
ReadStream.prototype._construct = _construct;
 
ReadStream.prototype._read = function(n) {
  n = this.pos !== undefined ?
    MathMin(this.end - this.pos + 1, n) :
    MathMin(this.end - this.bytesRead + 1, n);
 
  if (n <= 0) {
    this.push(null);
    return;
  }
 
  const buf = Buffer.allocUnsafeSlow(n);
 
  this[kIsPerformingIO] = true;
  this[kFs]
    .read(this.fd, buf, 0, n, this.pos, (er, bytesRead, buf) => {
      this[kIsPerformingIO] = false;
 
      // Tell ._destroy() that it's safe to close the fd now.
      if (this.destroyed) {
        this.emit(kIoDone, er);
        return;
      }
 
      if (er) {
        errorOrDestroy(this, er);
      } else if (bytesRead > 0) {
        if (this.pos !== undefined) {
          this.pos += bytesRead;
        }
 
        this.bytesRead += bytesRead;
 
        if (bytesRead !== buf.length) {
          // Slow path. Shrink to fit.
          // Copy instead of slice so that we don't retain
          // large backing buffer for small reads.
          const dst = Buffer.allocUnsafeSlow(bytesRead);
          buf.copy(dst, 0, 0, bytesRead);
          buf = dst;
        }
 
        this.push(buf);
      } else {
        this.push(null);
      }
    });
};
 
ReadStream.prototype._destroy = function(err, cb) {
  // Usually for async IO it is safe to close a file descriptor
  // even when there are pending operations. However, due to platform
  // differences file IO is implemented using synchronous operations
  // running in a thread pool. Therefore, file descriptors are not safe
  // to close while used in a pending read or write operation. Wait for
  // any pending IO (kIsPerformingIO) to complete (kIoDone).
  if (this[kIsPerformingIO]) {
    this.once(kIoDone, (er) => close(this, err || er, cb));
  } else {
    close(this, err, cb);
  }
};
 
ReadStream.prototype.close = function(cb) {
  if (typeof cb === 'function') finished(this, cb);
  this.destroy();
};
 
ObjectDefineProperty(ReadStream.prototype, 'pending', {
  __proto__: null,
  get() { return this.fd === null; },
  configurable: true
});
 
function WriteStream(path, options) {
  if (!(this instanceof WriteStream))
    return new WriteStream(path, options);
 
  options = copyObject(getOptions(options, kEmptyObject));
 
  // Only buffers are supported.
  options.decodeStrings = true;
 
  if (options.fd == null) {
    this.fd = null;
    this[kFs] = options.fs || fs;
    validateFunction(this[kFs].open, 'options.fs.open');
 
    // Path will be ignored when fd is specified, so it can be falsy
    this.path = toPathIfFileURL(path);
    this.flags = options.flags === undefined ? 'w' : options.flags;
    this.mode = options.mode === undefined ? 0o666 : options.mode;
 
    validatePath(this.path);
  } else {
    this.fd = getValidatedFd(importFd(this, options));
  }
 
  options.autoDestroy = options.autoClose === undefined ?
    true : options.autoClose;
 
  if (!this[kFs].write && !this[kFs].writev) {
    throw new ERR_INVALID_ARG_TYPE('options.fs.write', 'function',
                                   this[kFs].write);
  }
 
  if (this[kFs].write) {
    validateFunction(this[kFs].write, 'options.fs.write');
  }
 
  if (this[kFs].writev) {
    validateFunction(this[kFs].writev, 'options.fs.writev');
  }
 
  if (options.autoDestroy) {
    validateFunction(this[kFs].close, 'options.fs.close');
  }
 
  // It's enough to override either, in which case only one will be used.
  if (!this[kFs].write) {
    this._write = null;
  }
  if (!this[kFs].writev) {
    this._writev = null;
  }
 
  this.start = options.start;
  this.pos = undefined;
  this.bytesWritten = 0;
  this[kIsPerformingIO] = false;
 
  if (this.start !== undefined) {
    validateInteger(this.start, 'start', 0);
 
    this.pos = this.start;
  }
 
  ReflectApply(Writable, this, [options]);
 
  if (options.encoding)
    this.setDefaultEncoding(options.encoding);
}
ObjectSetPrototypeOf(WriteStream.prototype, Writable.prototype);
ObjectSetPrototypeOf(WriteStream, Writable);
 
ObjectDefineProperty(WriteStream.prototype, 'autoClose', {
  __proto__: null,
  get() {
    return this._writableState.autoDestroy;
  },
  set(val) {
    this._writableState.autoDestroy = val;
  }
});
 
const openWriteFs = deprecate(function() {
  // Noop.
}, 'WriteStream.prototype.open() is deprecated', 'DEP0135');
WriteStream.prototype.open = openWriteFs;
 
WriteStream.prototype._construct = _construct;
 
WriteStream.prototype._write = function(data, encoding, cb) {
  this[kIsPerformingIO] = true;
  this[kFs].write(this.fd, data, 0, data.length, this.pos, (er, bytes) => {
    this[kIsPerformingIO] = false;
    if (this.destroyed) {
      // Tell ._destroy() that it's safe to close the fd now.
      cb(er);
      return this.emit(kIoDone, er);
    }
 
    if (er) {
      return cb(er);
    }
 
    this.bytesWritten += bytes;
    cb();
  });
 
  if (this.pos !== undefined)
    this.pos += data.length;
};
 
WriteStream.prototype._writev = function(data, cb) {
  const len = data.length;
  const chunks = new Array(len);
  let size = 0;
 
  for (let i = 0; i < len; i++) {
    const chunk = data[i].chunk;
 
    chunks[i] = chunk;
    size += chunk.length;
  }
 
  this[kIsPerformingIO] = true;
  this[kFs].writev(this.fd, chunks, this.pos, (er, bytes) => {
    this[kIsPerformingIO] = false;
    if (this.destroyed) {
      // Tell ._destroy() that it's safe to close the fd now.
      cb(er);
      return this.emit(kIoDone, er);
    }
 
    if (er) {
      return cb(er);
    }
 
    this.bytesWritten += bytes;
    cb();
  });
 
  if (this.pos !== undefined)
    this.pos += size;
};
 
WriteStream.prototype._destroy = function(err, cb) {
  // Usually for async IO it is safe to close a file descriptor
  // even when there are pending operations. However, due to platform
  // differences file IO is implemented using synchronous operations
  // running in a thread pool. Therefore, file descriptors are not safe
  // to close while used in a pending read or write operation. Wait for
  // any pending IO (kIsPerformingIO) to complete (kIoDone).
  if (this[kIsPerformingIO]) {
    this.once(kIoDone, (er) => close(this, err || er, cb));
  } else {
    close(this, err, cb);
  }
};
 
WriteStream.prototype.close = function(cb) {
  if (cb) {
    if (this.closed) {
      process.nextTick(cb);
      return;
    }
    this.on('close', cb);
  }
 
  // If we are not autoClosing, we should call
  // destroy on 'finish'.
  if (!this.autoClose) {
    this.on('finish', this.destroy);
  }
 
  // We use end() instead of destroy() because of
  // https://github.com/nodejs/node/issues/2006
  this.end();
};
 
// There is no shutdown() for files.
WriteStream.prototype.destroySoon = WriteStream.prototype.end;
 
ObjectDefineProperty(WriteStream.prototype, 'pending', {
  __proto__: null,
  get() { return this.fd === null; },
  configurable: true
});
 
module.exports = {
  ReadStream,
  WriteStream
};