示例#1
0
const onRequest: Lifecycle.Method = (request, h) => {
    /*
     * Server events
     */
    request.server.events.on('request', (request: Request, event: any, tags: any) => {
        console.log(request.paramsArray);
        console.log(event);
        console.log(tags);
    });

    request.server.events.on('response', (request: Request) => {
        console.log('Response sent for request: ' + request.path);
    });

    request.server.events.on('start', () => {
        console.log('Server started');
    });

    request.server.events.once('stop', () => {
        console.log('Server stoped');
    });

    /*
     * Request events
     */
    const hash = Crypto.createHash('sha1');

    request.events.on("peek", (chunk) => {
        hash.update(chunk);
    });

    request.events.once("finish", () => {
        console.log(hash.digest('hex'));
    });

    request.events.once("disconnect", () => {
        console.error('request aborted');
    });

    return h.continue;
};
示例#2
0
文件: normalize.ts 项目: Volune/jest
const normalizeMissingOptions = (
  options: Config.InitialOptions,
  configPath: Config.Path | null | undefined,
  projectIndex: number,
): Config.InitialOptions => {
  if (!options.name) {
    options.name = crypto
      .createHash('md5')
      .update(options.rootDir)
      // In case we load config from some path that has the same root dir
      .update(configPath || '')
      .update(String(projectIndex))
      .digest('hex');
  }

  if (!options.setupFiles) {
    options.setupFiles = [];
  }

  return options;
};
示例#3
0
文件: builder.ts 项目: hUangDDD/bally
function safeBuild()
{
	console.log('files changed, start building');
	try
	{
		let _build_result = build();
		let _build_time = Date.now().toString() + Math.random().toString();
		let md5 = crypto.createHash('md5');
		build_result = _build_result;
		md5.update(build_result.body, 'utf8');
		md5.update(build_result.css, 'utf8');
		md5.update(build_result.javascript, 'utf8');
		build_version = md5.digest('hex');
		console.log('build ok. version=', build_version);
	}
	catch (e)
	{
		console.error('build error:', e);
		notifyToBuild();
	}
}
示例#4
0
app.post("/pop/search", (req, res) => {
    console.log("post /dot/search");
    // CREATE TABLE usanpn2.Pop_Search (Search_ID INT(11) NOT NULL AUTO_INCREMENT, Hash TEXT, Json TEXT, Save_Count INT(11), PRIMARY KEY(Search_ID));
    let foundHash = false;
    let saveCount = 1;
    let saveJson = JSON.stringify(req.body.searchJson);
    let hashedJson = crypto.createHash("md5").update(saveJson).digest("hex");
    pool.getConnection((err: any, connection: any) => {
        if (err) {
            console.error(err);
            res.send(null);
            connection.release();
        }
        else {
            connection.query("SELECT * from Pop_Search WHERE Hash = ?", hashedJson, (err: any, result: any) => {
                if (err) throw err;
                if (result[0]) {
                    foundHash = true;
                    saveCount = result[0].Save_Count;
                }
                if (!foundHash) {
                    let popSearch = {Hash: hashedJson, Json: saveJson, Save_Count: saveCount};
                    connection.query("INSERT INTO Pop_Search SET ?", popSearch, (err: any, result: any) => {
                        if (err) throw err;
                        console.log("Last insert:", result);
                        res.send({saved_search_hash: hashedJson});
                    });
                }
                else {
                    connection.query("Update Pop_Search SET Save_count = ? WHERE Hash = ?", [saveCount + 1, hashedJson], (err: any, result: any) => {
                        if (err) throw err;
                        console.log("Last insert:", result);
                        res.send({saved_search_hash: hashedJson});
                    });
                }
                connection.release();
            });
        }
    });
});
  return new Promise<ScanResults>(async (resolve, reject) => {
    // return a valid, if fake, result when there are no js files to hash.
    if (fileList.length === 0) {
      resolve(new ScanResultsImpl({}, new Map(), 'EMPTY-no-js-files'));
      return;
    }

    // TODO: Address the case where the array contains `undefined`.
    const hashes: Array<string | undefined> = [];
    const statistics: ScanStats = {};
    const errors: Map<string, Error> = new Map<string, Error>();

    for (const filename of fileList) {
      try {
        const fileStats = await statsForFile(filename, !precomputedHash);
        if (!precomputedHash) {
          hashes.push(fileStats.hash);
        }
        statistics[filename] = fileStats;
      } catch (err) {
        errors.set(filename, err);
      }
    }

    let hash: string;
    if (!precomputedHash) {
      // Sort the hashes to get a deterministic order as the files may
      // not be in the same order each time we scan the disk.
      const buffer = hashes.sort().join();
      const sha1 = crypto
        .createHash('sha1')
        .update(buffer)
        .digest('hex');
      hash = 'SHA1-' + sha1;
    } else {
      hash = precomputedHash!;
    }
    resolve(new ScanResultsImpl(statistics, errors, hash));
  });
示例#6
0
	const promise = new Promise<string | undefined>((c, e) => {
		const input = fs.createReadStream(path);
		const hash = crypto.createHash('sha1');
		const hashStream = hash as any as stream.PassThrough;
		input.pipe(hashStream);

		const done = once((err?: Error, result?: string) => {
			input.removeAllListeners();
			hashStream.removeAllListeners();

			if (err) {
				e(err);
			} else {
				c(result);
			}
		});

		input.once('error', done);
		input.once('end', done);
		hashStream.once('error', done);
		hashStream.once('data', (data: Buffer) => done(undefined, data.toString('hex')));
	});
示例#7
0
文件: tarball.ts 项目: dianpeng/fly
  return new Promise((resolve, reject) => {
    const pack = tarStream.pack()

    const outDir = path.dirname(outFile)
    if (!fs.existsSync(outDir)) {
      fs.mkdirpSync(outDir)
    }

    for (const { rootDir, files } of manifest) {
      for (const file of files) {
        const stat = fs.statSync(file)
        if (!stat.isFile()) {
          continue
        }
        const name = path.relative(rootDir, file)
        pack.entry({ name }, fs.readFileSync(file))
      }
    }

    pack.finalize()
    const gzip = zlib.createGzip()
    const outStream = fs.createWriteStream(outFile)
    const bundleHash = createHash("sha1").setEncoding("hex")
    pack.pipe(bundleHash)
    const gzStream = pack.pipe(gzip)
    gzStream.pipe(outStream)

    gzStream.on("end", () => {
      bundleHash.end()
      outStream.end()

      resolve({
        path: outFile,
        digest: bundleHash.read().toString(),
        byteLength: outStream.bytesWritten
      })
    })
  })
示例#8
0
    add('extension.startGhcid', () => {
        if (!vscode.workspace.rootPath) {
            vscode.window.showWarningMessage("You must open a workspace first.")
            return null;
        }
        // hashing the rootPath ensures we create a finite number of temp files
        var hash = crypto.createHash('sha256').update(vscode.workspace.rootPath).digest('hex').substring(0, 20);
        let file = path.join(os.tmpdir(), "ghcid-" + hash + ".txt");
        context.subscriptions.push({dispose: () => {try {fs.unlinkSync(file);} catch (e) {};}});
        fs.writeFileSync(file, "");

        let ghcidCommand : string = vscode.workspace.getConfiguration('ghcid').get('command');

        let opts : vscode.TerminalOptions =
            os.type().startsWith("Windows") ?
                {shellPath: "cmd.exe", shellArgs: ["/k", ghcidCommand]} :
                {shellPath: ghcidCommand, shellArgs: []};
        opts.name = "ghcid";
        opts.shellArgs.push("--outputfile=" + file);
        oldTerminal = vscode.window.createTerminal(opts);
        oldTerminal.show();
        return watchOutput(vscode.workspace.rootPath, file);
    });
示例#9
0
function RunCommand(CommandLabel: string) {
    var Editor = vscode.window.activeTextEditor;

    if (!Editor) return;

    var Selection = Editor.selection;
    if (Selection.isEmpty) return;

    var SelectedText = Editor.document.getText(Selection);

    var Output = null;

    if (/^base64.*$/.test(CommandLabel)) {
        if (CommandLabel[7] == 'e') Output = (new Buffer(SelectedText).toString('base64'));
        else Output = (new Buffer(SelectedText, 'base64').toString('ascii'));
    }
    else Output = crypto.createHash(CommandLabel).update(SelectedText).digest('hex');

    Editor.edit(editBuilder => {
        editBuilder.replace(Selection, SelectedText + " : " + Output);
    });

}
示例#10
0
    export function hash_string(str)
    {
        // NOTE: Comment the below line in for clearity
        // return str;

        // Get a list of supported hash functions
        var hash_functions = crypto.getHashes();
        //console.info(hash_functions);

        // Check if we have sha256 and sha1
        var priority_hash_functions = ["sha512", "sha384", "sha256", "sha1"];

        // Pick the best alternative
        var hash_function = null;
        for (var i = 0; i < priority_hash_functions.length; i++)
        {
            var hash = priority_hash_functions[i];
            var has_hash = (hash_functions.indexOf(hash) > -1);
            if(has_hash)
            {
                hash_function = crypto.createHash(hash);
                console.info("Using " + hash + " as hashing function");
                break;
            }
        }
        // No alternative present
        if(hash_function === null)
        {
            console.error("No adequate hash function present, terminating");
            process.exit(1);
        }

        // Do the actual string hashing
        var str_hash = hash_function.update(str).digest('hex');

        return str_hash.substring(0,5);
    }