How to use read-chunk - 10 common examples

To help you get started, we’ve selected a few read-chunk examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github elmadev / elmaonline-site / src / upload.js View on Github external
getReplaysByMd5(MD5).then(replaysMD5 => {
            if (replaysMD5.length > 0) {
              resolve({
                error: 'Duplicate',
                replayInfo: replaysMD5,
                file: filename,
              });
            } else {
              // find LevelIndex
              const replayCRC = readChunk.sync(
                `.${config.publicFolder}/temp/${uuid}-${filename}`,
                16,
                4,
              );
              let replayLevel = readChunk.sync(
                `.${config.publicFolder}/temp/${uuid}-${filename}`,
                20,
                12,
              );
              replayLevel = replayLevel.toString('utf-8').split('.')[0];
              getLevelsFromName(replayLevel).then(levels => {
                let LevelIndex = 0;
                levels.forEach(level => {
                  if (level.LevelData && replayCRC) {
                    if (
                      level.LevelData.toString('hex').substring(14, 22) ===
                      replayCRC.toString('hex')
                    ) {
                      LevelIndex = level.LevelIndex;
                    }
                  }
github citra-emu / citra-games-wiki / validation / app.js View on Github external
function validateImage(path, config) {
    if (fs.existsSync(path) === false) {
        validationError(`Image \"${path}\"' was not found at ${path}.`);
    } else {
        // Read first 12 bytes (enough for '%PNG', etc)
        const buffer = readChunk.sync(path, 0, 12);
        const type = imageType(buffer).mime;
        if (type !== config.type) {
            validationError(`Incorrect format of image (${type} != ${config.type})`);
        }

        let dimensions = sizeOf(path);

        for (const sizeIndex in config.sizes) {
            const size = config.sizes[sizeIndex];

            if (dimensions.width === size.width && dimensions.height === size.height) {
                return;
            }
        }

        // Build our error message
github vorg / kollektor / lib / generate-thumbnail.js View on Github external
function generateThumbnail (orig, thumb, w, callback) {
  log('Generate Thumbnail', orig)
  const buffer = readChunk.sync(orig, 0, 262)
  const extInfo = fileType(buffer)
  const ext = extInfo ? extInfo.ext : null
  if (!ext) {
    return callback(new Error('Unknown file type'), null)
  }
  if (ext === 'gif') {
    execFile(gifsicle, ['--resize', `${w / 2}x_`, orig, '-o', thumb], (err) => {
      callback(err, thumb)
    })
  } else { // jpeg, png
    jimp.read(orig)
      .then((img) => {
        log('jimp resize', w, thumb)
        img.resize(w, jimp.AUTO).getBuffer(jimp.MIME_JPEG, (err, buf) => {
          log('jimp resize done', err)
          fs.writeFileSync(thumb, buf)
github expo / expo-cli / libraries / schemer / src / index.js View on Github external
meta: Meta,
  }) {
    if (meta && meta.asset && data) {
      const { asset, dimensions, square, contentTypePattern, contentTypeHuman }: Meta = meta;
      // filePath could be an URL
      const filePath = path.resolve(this.rootDir, data);
      try {
        // Assumption: All assets are images. This may change in the future.
        // NOTE(nikki): The '4100' below should be enough for most file types, though we
        //              could probably go shorter....
        //              http://www.garykessler.net/library/file_sigs.html
        //  The metadata content for .jpgs might be located a lot farther down the file, so this
        //  may pose problems in the future.
        //  This cases on whether filePath is a remote URL or located on the machine
        const probeResult = fs.existsSync(filePath)
          ? imageProbe.sync(await readChunk(filePath, 0, 4100))
          : await imageProbe(data, { useElectronNet: false });

        const { width, height, type, mime, wUnits, hUnits } = probeResult;

        if (contentTypePattern && !mime.match(new RegExp(contentTypePattern))) {
          this.manualValidationErrors.push(
            new ValidationError({
              errorCode: ErrorCodes.INVALID_CONTENT_TYPE,
              fieldPath,
              message: `field '${fieldPath}' should point to ${meta.contentTypeHuman} but the file at '${data}' has type ${type}`,
              data,
              meta,
            })
          );
        }
github FreeFeed / freefeed-server / app / models / attachment.js View on Github external
async function mimeTypeDetect(fileName, filePath) {
  // The file type is detected by checking the magic number of the buffer.
  // It only needs the first "minimumBytes" bytes.
  const buffer = await readChunk(filePath, 0, fileType.minimumBytes);
  const info = fileType(buffer);

  if (info && info.mime && info.mime !== 'application/octet-stream') {
    return info.mime;
  }

  // legacy mmmagic based detection
  let mimeType = 'application/octet-stream';

  try {
    mimeType = await detectMime(filePath);

    if (mimeType === 'application/octet-stream') {
      const typeOfFile = await detectFile(filePath);

      if (typeOfFile.startsWith('Audio file with ID3')) {
github expo / expo-cli / packages / schemer / src / index.ts View on Github external
async _validateImageAsync({ fieldPath, data, meta }: AssetField) {
    if (meta && meta.asset && data) {
      const { dimensions, square, contentTypePattern }: Meta = meta;
      // filePath could be an URL
      const filePath = path.resolve(this.rootDir, data);
      try {
        // NOTE(nikki): The '4100' below should be enough for most file types, though we
        //              could probably go shorter....
        //              http://www.garykessler.net/library/file_sigs.html
        //  The metadata content for .jpgs might be located a lot farther down the file, so this
        //  may pose problems in the future.
        //  This cases on whether filePath is a remote URL or located on the machine
        const probeResult = fs.existsSync(filePath)
          ? imageProbe.sync(await readChunk(filePath, 0, 4100))
          : await imageProbe(data, { useElectronNet: false });
        if (!probeResult) {
          return;
        }

        const { width, height, type, mime } = probeResult;

        if (contentTypePattern && !mime.match(new RegExp(contentTypePattern))) {
          this.manualValidationErrors.push(
            new ValidationError({
              errorCode: 'INVALID_CONTENT_TYPE',
              fieldPath,
              message: `field '${fieldPath}' should point to ${meta.contentTypeHuman} but the file at '${data}' has type ${type}`,
              data,
              meta,
            })
github thammin / node-bpg / test / encoderSpec.js View on Github external
.map(file => {
      var buffer = readChunk.sync(file, 0, 4);
      t.true(isBpg(buffer));
    }).then(() => t.end());
  });
github audiojs / audio-type / cli.js View on Github external
help();
	return;
}

if (process.argv.indexOf('-v') !== -1 || process.argv.indexOf('--version') !== -1) {
	console.log(pkg.version);
	return;
}

if (process.stdin.isTTY) {
	if (!input) {
		help();
		return;
	}

	init(readChunk.sync(input, 0, 12));
} else {
	process.stdin.once('data', function (data) {
		init(data);
	});
}
github kube-HPC / hkube / core / api-server / lib / service / builds.js View on Github external
async _fileInfo(file) {
        const bufferExt = readChunk.sync(file.path, 0, fileType.minimumBytes);
        let fileExt = fileType(bufferExt);
        if (fileExt) {
            fileExt = fileExt.ext;
        }
        else {
            const ext = path.extname(file.name).split('.');
            fileExt = ext[ext.length - 1];
        }

        const checksum = await this._checkSum(file.path);
        const fileSize = fse.statSync(file.path).size;
        return { fileExt, checksum, fileSize };
    }
github apache / cordova-common / src / ConfigChanges / ConfigFile.js View on Github external
function isBinaryPlist (filename) {
    return readChunk.sync(filename, 0, 6).toString() === 'bplist';
}

read-chunk

Read a chunk from a file

MIT
Latest version published 4 months ago

Package Health Score

75 / 100
Full package analysis

Popular read-chunk functions