Best JavaScript code snippet using root
inspect.js
Source:inspect.js
1'use strict';2const crypto = require('crypto');3const pathUtil = require('path');4const fs = require('./utils/fs');5const validate = require('./utils/validate');6const supportedChecksumAlgorithms = ['md5', 'sha1', 'sha256', 'sha512'];7const symlinkOptions = ['report', 'follow'];8const validateInput = (methodName, path, options) => {9 const methodSignature = `${methodName}(path, [options])`;10 validate.argument(methodSignature, 'path', path, ['string']);11 validate.options(methodSignature, 'options', options, {12 checksum: ['string'],13 mode: ['boolean'],14 times: ['boolean'],15 absolutePath: ['boolean'],16 symlinks: ['string'],17 });18 if (options && options.checksum !== undefined19 && supportedChecksumAlgorithms.indexOf(options.checksum) === -1) {20 throw new Error(`Argument "options.checksum" passed to ${methodSignature} must have one of values: ${supportedChecksumAlgorithms.join(', ')}`);21 }22 if (options && options.symlinks !== undefined23 && symlinkOptions.indexOf(options.symlinks) === -1) {24 throw new Error(`Argument "options.symlinks" passed to ${methodSignature} must have one of values: ${symlinkOptions.join(', ')}`);25 }26};27const createInspectObj = (path, options, stat) => {28 const obj = {};29 obj.name = pathUtil.basename(path);30 if (stat.isFile()) {31 obj.type = 'file';32 obj.size = stat.size;33 } else if (stat.isDirectory()) {34 obj.type = 'dir';35 } else if (stat.isSymbolicLink()) {36 obj.type = 'symlink';37 } else {38 obj.type = 'other';39 }40 if (options.mode) {41 obj.mode = stat.mode;42 }43 if (options.times) {44 obj.accessTime = stat.atime;45 obj.modifyTime = stat.mtime;46 obj.changeTime = stat.ctime;47 }48 if (options.absolutePath) {49 obj.absolutePath = path;50 }51 return obj;52};53// ---------------------------------------------------------54// Sync55// ---------------------------------------------------------56const fileChecksum = (path, algo) => {57 const hash = crypto.createHash(algo);58 const data = fs.readFileSync(path);59 hash.update(data);60 return hash.digest('hex');61};62const addExtraFieldsSync = (path, inspectObj, options) => {63 if (inspectObj.type === 'file' && options.checksum) {64 inspectObj[options.checksum] = fileChecksum(path, options.checksum);65 } else if (inspectObj.type === 'symlink') {66 inspectObj.pointsAt = fs.readlinkSync(path);67 }68};69const inspectSync = (path, options) => {70 let statOperation = fs.lstatSync;71 let stat;72 const opts = options || {};73 if (opts.symlinks === 'follow') {74 statOperation = fs.statSync;75 }76 try {77 stat = statOperation(path);78 } catch (err) {79 // Detection if path exists80 if (err.code === 'ENOENT') {81 // Doesn't exist. Return undefined instead of throwing.82 return undefined;83 }84 throw err;85 }86 const inspectObj = createInspectObj(path, opts, stat);87 addExtraFieldsSync(path, inspectObj, opts);88 return inspectObj;89};90// ---------------------------------------------------------91// Async92// ---------------------------------------------------------93const fileChecksumAsync = (path, algo) => {94 return new Promise((resolve, reject) => {95 const hash = crypto.createHash(algo);96 const s = fs.createReadStream(path);97 s.on('data', (data) => {98 hash.update(data);99 });100 s.on('end', () => {101 resolve(hash.digest('hex'));102 });103 s.on('error', reject);104 });105};106const addExtraFieldsAsync = (path, inspectObj, options) => {107 if (inspectObj.type === 'file' && options.checksum) {108 return fileChecksumAsync(path, options.checksum)109 .then((checksum) => {110 inspectObj[options.checksum] = checksum;111 return inspectObj;112 });113 } else if (inspectObj.type === 'symlink') {114 return fs.readlink(path)115 .then((linkPath) => {116 inspectObj.pointsAt = linkPath;117 return inspectObj;118 });119 }120 return Promise.resolve(inspectObj);121};122const inspectAsync = (path, options) => {123 return new Promise((resolve, reject) => {124 let statOperation = fs.lstat;125 const opts = options || {};126 if (opts.symlinks === 'follow') {127 statOperation = fs.stat;128 }129 statOperation(path)130 .then((stat) => {131 const inspectObj = createInspectObj(path, opts, stat);132 addExtraFieldsAsync(path, inspectObj, opts)133 .then(resolve, reject);134 })135 .catch((err) => {136 // Detection if path exists137 if (err.code === 'ENOENT') {138 // Doesn't exist. Return undefined instead of throwing.139 resolve(undefined);140 } else {141 reject(err);142 }143 });144 });145};146// ---------------------------------------------------------147// API148// ---------------------------------------------------------149exports.supportedChecksumAlgorithms = supportedChecksumAlgorithms;150exports.symlinkOptions = symlinkOptions;151exports.validateInput = validateInput;152exports.sync = inspectSync;...
main.ts
Source:main.ts
...88 'show custom raw info (provide systeminformation function name)',89 }),90 async args => {91 if (args.os) {92 console.log('OS:', inspectObj(await si.osInfo()));93 }94 if (args.cpu) {95 console.log('CPU:', inspectObj(await si.cpu()));96 console.log('CPU Load:', inspectObj(await si.currentLoad()));97 console.log('CPU Temp:', inspectObj(await si.cpuTemperature()));98 }99 if (args.ram) {100 console.log('Mem:', inspectObj(await si.mem()));101 console.log('Mem Layout:', inspectObj(await si.memLayout()));102 }103 if (args.storage) {104 console.log('Disk Layout:', inspectObj(await si.diskLayout()));105 console.log('FS Size:', inspectObj(await si.fsSize()));106 console.log('Block Devices:', inspectObj(await si.blockDevices()));107 }108 if (args.network) {109 console.log(110 'Network Interfaces:',111 inspectObj(await si.networkInterfaces())112 );113 console.log('Network Stats:', inspectObj(await si.networkStats()));114 }115 if (args.gpu) {116 console.log('Graphics:', inspectObj(await si.graphics()));117 }118 if (args.custom) {119 console.log(120 `Custom [${args.custom}]:`,121 inspectObj(await si[args.custom]())122 );123 }124 }125 )126 .demandCommand(1, 1, 'You need to specify a single command')127 .strict()...
index.ts
Source:index.ts
1#!/usr/bin/env node2import commander from "commander"3import chalk from "chalk"4import { Inspector, URLsMatchingSet } from "./inspector"5import { ConsoleReporter, JUnitReporter } from "./report"6import fs from "fs/promises"7commander8 .version("1.4.0")9 .description("Extract and recursively check all URLs reporting broken ones\n\nDedicated to Daria Bogatova \u2665")10commander11 .command("inspect <url>|<file://>")12 .description("Check links in the given URL or a text file")13 .option("-r, --recursive", "recursively check all links in all URLs within supplied host (ignored for file://)", false)14 .option("-t, --timeout <number>", "timeout in ms after which the link will be considered broken", (value: string, _) => parseInt(value), 2000)15 .option("-g, --get", "use GET request instead of HEAD", false)16 .option("-s, --skip <globs>", "URLs to skip defined by globs, like '*linkedin*'", (value: string, previous: string[]) => previous.concat([value]), [])17 .option("--reporters <coma-separated-strings>", "Reporters to use in processing the results (junit, console)", (value: string, _) => value.split(","), ["console"])18 .option("--retries <number>", "The number of times to retry TIMEOUT URLs", (value: string, _) => parseInt(value), 3)19 .option("--user-agent <string>", "The User-Agent header", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1 Safari/605.1.15")20 .option("--ignore-prefixes <coma-separated-strings>", "prefix(es) to ignore (without ':'), like mailto: and tel:", (value: string, _) => value.split(","), ["javascript", "data", "mailto", "sms", "tel", "geo"])21 .option("--accept-codes <coma-separated-numbers>", "HTTP response code(s) (beyond 200-299) to accept, like 999 for linkedin", (value: string, _) => value.split(",").map(code => parseInt(code)), [999])22 .option("--ignore-skipped", "Do not report skipped URLs", false)23 .option("--single-threaded", "Do not enable parallelization", false)24 .option("-v, --verbose", "log progress of checking URLs", false)25 .action(async (url: string, inspectObj) => {26 const urls: URL[] = []27 if (url.startsWith("file://")) {28 const file = await fs.readFile(url.replace("file://", ""), "utf-8")29 for (const line of file.toString().split("\n")) {30 if (!line.trim()) {31 continue32 }33 try {34 const url = new URL(line)35 urls.push(url)36 console.log(`From file: ${line}`)37 } catch (e) {38 console.warn(chalk.yellow(`${line} does not look a like valid URL`))39 }40 }41 } else {42 try {43 urls.push(new URL(url))44 } catch (e) {45 console.error(chalk.red(`${url} does not look like a valid URL (forgot http(s)?)`))46 process.exit(1)47 }48 }49 const inspector = new Inspector(new URLsMatchingSet(), {50 acceptedCodes: inspectObj.acceptCodes as number[],51 timeout: parseInt(inspectObj.timeout as string),52 ignoredPrefixes: inspectObj.ignorePrefixes as string[],53 skipURLs: inspectObj.skip as string[],54 verbose: inspectObj.verbose as boolean,55 get: inspectObj.get as boolean,56 ignoreSkipped: inspectObj.ignoreSkipped as boolean,57 singleThreaded: inspectObj.singleThreaded as boolean,58 disablePrint: false,59 retries: inspectObj.retries as number,60 userAgent: inspectObj.userAgent as string61 })62 if (urls.length == 0) {63 process.exit(0)64 }65 const result = await inspector.processURL(urls, inspectObj.recursive, url.startsWith("file://"))66 for (const reporter of inspectObj.reporters as string[]) {67 switch (reporter) {68 case "junit":69 result.report(new JUnitReporter())70 break71 case "console":72 result.report(new ConsoleReporter())73 break74 }75 }76 process.exit(result.success() ? 0 : 1)77 })78if (!process.argv.slice(2).length) {79 commander.outputHelp()80 process.exit()81}...
Using AI Code Generation
1var obj = {name: 'John', age: 31, city: 'New York'};2var inspect = require('util').inspect;3console.log(inspect(obj));4var util = require('util');5var obj = {name: 'John', age: 31, city: 'New York'};6console.log(util.inspect(obj));7var obj = {name: 'John', age: 31, city: 'New York'};8console.log(util.inspect(obj, {colors: true}));9var obj = {name: 'John', age: 31, city: 'New York'};10console.log(util.inspect(obj, {showHidden: true, depth: null}));11var obj = {name: 'John', age: 31, city: 'New York'};12console.log(util.inspect(obj, {showHidden: true, depth: null, colors: true}));13var obj = {name: 'John', age: 31, city: 'New York'};14console.log(util.inspect(obj, {showHidden: true, depth: null, colors: true, customInspect: true}));15var obj = {name: 'John', age: 31, city: 'New York'};16console.log(util.inspect(obj, {showHidden: true, depth: null, colors: true, customInspect: true, showProxy: true
Using AI Code Generation
1var obj = {a:1, b:2, c:3};2var root = require('./root');3root.inspectObj(obj);4module.exports.inspectObj = function(obj) {5 console.log(obj);6};7var obj = {a:1, b:2, c:3};8var root = require('./root');9root.inspectObj(obj);10module.exports = {11 inspectObj: function(obj) {12 console.log(obj);13 }14};15var obj = {a:1, b:2, c:3};16var root = require('./root');17root.inspectObj(obj);18module.exports = {19 inspectObj: function(obj) {20 console.log(obj);21 }22};23var obj = {a:1, b:2, c:3};24var root = require('./root');25root.inspectObj(obj);26module.exports = {27 inspectObj: function(obj) {28 console.log(obj);29 }30};31var obj = {a:1, b:2, c:3};32var root = require('./root');33root.inspectObj(obj);34module.exports = {35 inspectObj: function(obj) {36 console.log(obj);37 }38};39var obj = {a:1, b:2, c:3};40var root = require('./root');41root.inspectObj(obj);42module.exports = {43 inspectObj: function(obj) {44 console.log(obj);45 }46};47var obj = {a:1, b:2, c:3};48var root = require('./root');49root.inspectObj(obj);
Using AI Code Generation
1var inspectObj = require('./root').inspectObj;2var obj = {3 address: {4 }5};6inspectObj(obj);7[object Object] {8 address: [object Object] {9 }10}11function inspectObj(obj) {12 var util = require('util');13 console.log(util.inspect(obj, false, null));14}15exports.inspectObj = inspectObj;
Using AI Code Generation
1var obj = {2};3inspectObj(obj);4var obj = {5};6inspectObj(obj);7var obj = {8};9inspectObj(obj);10var obj = {11};12inspectObj(obj);13var obj = {14};15inspectObj(obj);16var obj = {17};18inspectObj(obj);19var obj = {20};21inspectObj(obj);22var obj = {23};24inspectObj(obj);25var obj = {26};27inspectObj(obj);28var obj = {29};30inspectObj(obj);31var obj = {32};33inspectObj(obj);34var obj = {35};36inspectObj(obj);37var obj = {38};39inspectObj(obj);
Using AI Code Generation
1var inspectObj = require('util').inspect;2var obj = {name:'John', age: 20};3console.log(inspectObj(obj));4var util = require('util');5var obj = {name:'John', age: 20};6console.log(util.inspect(obj));7var util = require('util');8var obj = {name:'John', age: 20};9console.log(util.inspect(obj, false, null));10var util = require('util');11var obj = {name:'John', age: 20};12console.log(util.inspect(obj, true, null));13var util = require('util');14var obj = {name:'John', age: 20};15console.log(util.inspect(obj, true, 2));16var util = require('util');17var obj = {name:'John', age: 20};18console.log(util.inspect(obj, true, 3));19var util = require('util');20var obj = {name:'John', age: 20};21console.log(util.inspect(obj, true, 4));22var util = require('util');23var obj = {name:'John', age: 20};24console.log(util.inspect(obj, true, 5));25var util = require('util');26var obj = {name:'John', age: 20};27console.log(util.inspect(obj, true, 6));
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!