fs#createReadStream JavaScript Examples

The following examples show how to use fs#createReadStream. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: compress.js    From ucompress with ISC License 6 votes vote down vote up
br = (source, mode) => new Promise((res, rej) => {
  const dest = source + '.br';
  stat(source, (err, stats) => {
    /* istanbul ignore next */
    if (err) rej(err);
    else pipeline(
      createReadStream(source),
      createBrotliCompress({
        [BROTLI_PARAM_SIZE_HINT]: stats.size,
        [BROTLI_PARAM_QUALITY]: BROTLI_MAX_QUALITY,
        [BROTLI_PARAM_MODE]: mode == 'text' ?
          BROTLI_MODE_TEXT : (
            mode === 'font' ?
              BROTLI_MODE_FONT :
              /* istanbul ignore next */
              BROTLI_MODE_GENERIC
          )
      }),
      createWriteStream(dest),
      err => {
        /* istanbul ignore next */
        if (err) rej(err);
        else res(dest);
      }
    );
  });
})
Example #2
Source File: compress.js    From ucompress with ISC License 6 votes vote down vote up
deflate = source => new Promise((res, rej) => {
  const dest = source + '.deflate';
  pipeline(
    createReadStream(source),
    createDeflate(zlibDefaultOptions),
    createWriteStream(dest),
    err => {
      /* istanbul ignore next */
      if (err) rej(err);
      else res(dest);
    }
  );
})
Example #3
Source File: compress.js    From ucompress with ISC License 6 votes vote down vote up
gzip = source => new Promise((res, rej) => {
  const dest = source + '.gzip';
  pipeline(
    createReadStream(source),
    createGzip(zlibDefaultOptions),
    createWriteStream(dest),
    err => {
      /* istanbul ignore next */
      if (err) rej(err);
      else res(dest);
    }
  );
})
Example #4
Source File: headers.js    From ucompress with ISC License 6 votes vote down vote up
getHash = source => new Promise(res => {
  const hash = createHash('sha1');
  const input = createReadStream(source);
  input.on('readable', () => {
    const data = input.read();
    if (data)
      hash.update(data, 'utf-8');
    else
      res(hash.digest('base64'));
  });
})
Example #5
Source File: helpers.js    From v8-deopt-viewer with MIT License 6 votes vote down vote up
export function decompress(inputPath) {
	return new Promise((resolve, reject) => {
		const stream = createReadStream(inputPath)
			.pipe(zlib.createBrotliDecompress())
			.pipe(createWriteStream(inputPath.replace(/.br$/, "")));

		stream
			.on("end", resolve)
			.on("close", resolve)
			.on("finish", resolve)
			.on("error", reject);
	});
}
Example #6
Source File: index.js    From OpenEDR with GNU General Public License v3.0 6 votes vote down vote up
/**
   * @method analyze A shortcut for `Client.analysis.analyze()` but that will convert a file's path to a readable stream beforehand.
   * @param {String/Readable} file The file's path or Reable stream.
   * @param  {...any} options
   * @returns {Promise<String>} The analysis' URL.
   */
  async analyze(file, ...options) {
    if (!(file instanceof Readable) && typeof file == 'string')
      file = createReadStream(file);

    return this.analysis.analyze(file, ...options);
  }
Example #7
Source File: cli.js    From modeligado with MIT License 6 votes vote down vote up
processFile = async () => {
  const records = []
  const parser = createReadStream('./projeto.csv')
    .pipe(parse({
      from_line: 2
    }))

  const server = http.createServer((req, res) => serveHandler(req, res, {
    public: '../' // folder of files to serve
  })).listen(8080)

  const browser = await puppeteer.launch({ defaultViewport: { width: 4000, height: 2000 } })

  for await (const record of parser) {
    await createUML(browser, record[1], record[0] + '.png')
  }

  await browser.close()
  server.close()
  return records
}
Example #8
Source File: index.js    From kit with MIT License 6 votes vote down vote up
/**
 * @param {string} file
 * @param {'gz' | 'br'} format
 */
async function compress_file(file, format = 'gz') {
	const compress =
		format == 'br'
			? zlib.createBrotliCompress({
					params: {
						[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
						[zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
						[zlib.constants.BROTLI_PARAM_SIZE_HINT]: statSync(file).size
					}
			  })
			: zlib.createGzip({ level: zlib.constants.Z_BEST_COMPRESSION });

	const source = createReadStream(file);
	const destination = createWriteStream(`${file}.${format}`);

	await pipe(source, compress, destination);
}
Example #9
Source File: index.js    From kit with MIT License 6 votes vote down vote up
/**
 * @param {string} file
 * @param {'gz' | 'br'} format
 */
async function compress_file(file, format = 'gz') {
	const compress =
		format == 'br'
			? zlib.createBrotliCompress({
					params: {
						[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
						[zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
						[zlib.constants.BROTLI_PARAM_SIZE_HINT]: statSync(file).size
					}
			  })
			: zlib.createGzip({ level: zlib.constants.Z_BEST_COMPRESSION });

	const source = createReadStream(file);
	const destination = createWriteStream(`${file}.${format}`);

	await pipe(source, compress, destination);
}
Example #10
Source File: server.js    From asymptoteWebApplication with GNU Lesser General Public License v3.0 6 votes vote down vote up
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    Iframe Request
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
app.use("/clients", (req, res, next) => {
  if (req.method === "GET") {
    const fileToServe = __dirname + req.originalUrl;
    if (existsSync(fileToServe)) {
      createReadStream(fileToServe).pipe(res);
    }
  } else {
    next();
  }
});
Example #11
Source File: send-file.js    From nanoexpress with Apache License 2.0 5 votes vote down vote up
export default function sendFile(
  path,
  lastModified = true,
  compressed = false
) {
  const req = this.__request;
  const { headers } = req;
  const responseHeaders = {};

  const stat = statSync(path);
  let { size } = stat;

  // handling last modified
  if (lastModified) {
    const { mtime } = stat;

    mtime.setMilliseconds(0);
    const mtimeutc = mtime.toUTCString();

    // Return 304 if last-modified
    if (headers && headers['if-modified-since']) {
      if (new Date(headers['if-modified-since']) >= mtime) {
        this.writeStatus('304 Not Modified');
        return this.end();
      }
    }
    responseHeaders['last-modified'] = mtimeutc;
  }
  responseHeaders['content-type'] = getMime(path);

  // write data
  let start = 0;
  let end = 0;

  if (headers && headers.range) {
    [start, end] = headers.range
      .substr(6)
      .split('-')
      .map((byte) => (byte ? parseInt(byte, 10) : undefined));

    // Chrome patch for work
    if (end === undefined) {
      end = size - 1;
    }

    if (start !== undefined) {
      this.writeStatus('206 Partial Content');
      responseHeaders['accept-ranges'] = 'bytes';
      responseHeaders['content-range'] = `bytes ${start}-${end}/${size}`;
      size = end - start + 1;
    }
  }

  // for size = 0
  if (end < 0) {
    end = 0;
  }

  req.responseHeaders = responseHeaders;

  const createStreamInstance = end
    ? createReadStream(path, { start, end })
    : createReadStream(path);

  const pipe = this.pipe(createStreamInstance, size, compressed);
  this.writeHeaders(responseHeaders);

  return pipe;
}