fs#readFileSync JavaScript Examples

The following examples show how to use fs#readFileSync. 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: rollup-plugin-dataurl.js    From highway-404 with MIT License 6 votes vote down vote up
dataurl = () => ({
    name: 'rollup-plugin-dataurl',

    transform: (source, id) => {
      let transformedCode = source;

      // find all DATAURL placeholders, capture the filepaths
      const matches = [...source.matchAll(/ (.*) = 'DATAURL:(.*)'/g)];

      matches.forEach(([, variable, imageFilePath]) => {
        console.log('found ', variable, imageFilePath);
        // read the image binary content
        const data = readFileSync(`./${imageFilePath}`);
        // replace the placeholder by a base64 encoded dataurl of the image
        transformedCode = transformedCode.replace(
          ` ${variable} = 'DATAURL:${imageFilePath}'`,
          ` ${variable} = 'data:image/png;base64,${data.toString('base64')}'`
        );
      });

      console.log('dataurl plugin done with', id);
      return {
        code: transformedCode,
        map: { mappings: ''}
      };
    }
  })
Example #2
Source File: lint-versions.js    From rocket with MIT License 6 votes vote down vote up
function readPackageJsonNameVersion(filePath) {
  if (existsSync(filePath)) {
    const jsonData = JSON.parse(readFileSync(filePath, 'utf-8'));
    const result = {};
    result[jsonData.name] = `^${jsonData.version}`;
    return result;
  }
  return {};
}
Example #3
Source File: gulpfile.babel.js    From redhat-workshop-openshift-pipelines with Apache License 2.0 6 votes vote down vote up
//Watch Paths
function watchGlobs() {
  let json_content = readFileSync(`${__dirname}/${filename}`, "UTF-8");
  let yaml_content = yamlLoad(json_content);
  let dirs = yaml_content.content.sources.map(source => [
    `${source.url}/**/**.yml`,
    `${source.url}/**/**.adoc`,
    `${source.url}/**/**.hbs`
  ]); 
  dirs.push(["dev-site.yml"]);
  dirs = [].concat(...dirs);
  //console.log(dirs);
  return dirs;
}
Example #4
Source File: searchRuntimeDependencies.spec.js    From js-x-ray with MIT License 6 votes vote down vote up
test("should be capable to follow hexa computation members expr", (tape) => {
  const advancedComputation = readFileSync(join(FIXTURE_PATH, "advanced-computation.js"), "utf-8");
  const { warnings, dependencies } = runASTAnalysis(advancedComputation);

  tape.deepEqual(getWarningKind(warnings), [
    "encoded-literal",
    "unsafe-assign",
    "unsafe-assign",
    "unsafe-import",
    "unsafe-stmt"
  ].sort());
  tape.deepEqual([...dependencies], ["./test/data"]);
  tape.end();
});
Example #5
Source File: outbox-store.js    From medusa with MIT License 6 votes vote down vote up
async flushFile(filePath, flushOperation) {
    const now = `${Date.now()}-${process.pid}`
    let success = false
    let contents = ``
    try {
      if (!existsSync(filePath)) {
        return true
      }
      // Unique temporary file name across multiple concurrent Medusa instances
      const newPath = `${this.bufferFilePath}-${now}`
      renameSync(filePath, newPath)
      contents = readFileSync(newPath, `utf8`)
      unlinkSync(newPath)

      // There is still a chance process dies while sending data and some events are lost
      // This will be ok for now, however
      success = await flushOperation(contents)
    } catch (e) {
      if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
        console.error("Failed to perform file flush", e)
      }
    } finally {
      // if sending fails, we write the data back to the log
      if (!success) {
        if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
          console.error(
            "File flush did not succeed - writing back to file",
            success
          )
        }
        this.appendToBuffer(contents)
      }
    }
    return true
  }
Example #6
Source File: AlphaFilter.js    From inkpaint with MIT License 6 votes vote down vote up
constructor(alpha = 1.0) {
    super(
      // vertex shader
      readFileSync(join(__dirname, "../fragments/default.vert"), "utf8"),
      // fragment shader
      readFileSync(join(__dirname, "./alpha.frag"), "utf8")
    );

    this.alpha = alpha;
    this.glShaderKey = "alpha";
  }
Example #7
Source File: index.js    From SJTU-Application with MIT License 6 votes vote down vote up
async _loadFile(filePath) {
    debug('docsify')(`load > ${filePath}`)
    let content
    try {
      if (isAbsolutePath(filePath)) {
        const res = await fetch(filePath)
        if (!res.ok) {
          throw Error()
        }
        content = await res.text()
        this.lock = 0
      } else {
        content = await readFileSync(filePath, 'utf8')
        this.lock = 0
      }
      return content
    } catch (e) {
      this.lock = this.lock || 0
      if (++this.lock > 10) {
        this.lock = 0
        return
      }

      const fileName = basename(filePath)
      const result = await this._loadFile(
        resolvePathname(`../${fileName}`, filePath)
      )

      return result
    }
  }
Example #8
Source File: index.js    From ip-index with GNU General Public License v3.0 6 votes vote down vote up
readFileSync(`${__dirname}/../data/asns.csv`).toString().split(/\s+/).forEach((item, index) => {
  if (!index) {
    return undefined;
  }

  const [asn, handle, country, description] = item.split(',');

  asns[asn] = {
    handle,
    description: (description || '').trim().replace(/"/g, ''),
    country: country === '-' ? null : country,
  };
});
Example #9
Source File: DisplacementFilter.js    From inkpaint with MIT License 6 votes vote down vote up
constructor(sprite, scale) {
    const maskMatrix = new core.Matrix();

    sprite.renderable = false;

    super(
      // vertex shader
      readFileSync(
        join(__dirname, "../fragments/default-filter-matrix.vert"),
        "utf8"
      ),
      // fragment shader
      readFileSync(join(__dirname, "./displacement.frag"), "utf8")
    );

    this.maskSprite = sprite;
    this.maskMatrix = maskMatrix;

    this.uniforms.mapSampler = sprite._texture;
    this.uniforms.filterMatrix = maskMatrix;
    this.uniforms.scale = { x: 1, y: 1 };

    if (scale === null || scale === undefined) {
      scale = 20;
    }

    this.scale = new core.Point(scale, scale);
  }
Example #10
Source File: index.js    From ip-index with GNU General Public License v3.0 6 votes vote down vote up
readFileSync(`${__dirname}/../data/asns_cidrs.csv`).toString()
  .split(/\s+/)
  .filter((i) => i)
  .forEach((item, index) => {
    if (!index) {
      return null;
    }

    const [asn, cidr, first, last] = item.split(',');

    const rangeIndex = +cidr.split('.')[0];

    if (!rangesIndexed[rangeIndex]) {
      rangesIndexed[rangeIndex] = [];
    }

    const range = {
      start: +first,
      end: +last,
      subnet: cidr,
      asn: +asn,
      hosting: !!dcAsns[asn],
    };

    if (asns[asn]) {
      asns[asn].subnetsNum = (asns[asn].subnetsNum || 0) + 1;
    }

    rangesIndexed[rangeIndex].push(range);
  });
Example #11
Source File: weakCrypto.spec.js    From js-x-ray with MIT License 6 votes vote down vote up
test("it should report a warning in case of `[expression]createHash(<weak-algo>)` usage", async(tape) => {
  const fixturesDir = join(FIXTURE_PATH, "memberExpression");
  const fixtureFiles = await readdir(fixturesDir);

  for (const fixtureFile of fixtureFiles) {
    const fixture = readFileSync(join(fixturesDir, fixtureFile), "utf-8");
    const { warnings: outputWarnings } = runASTAnalysis(fixture);

    const [firstWarning] = outputWarnings;
    tape.strictEqual(outputWarnings.length, 1);
    tape.deepEqual(firstWarning.kind, "weak-crypto");
    tape.strictEqual(firstWarning.value, fixtureFile.split(".").at(0));
    tape.strictEqual(firstWarning.experimental, true);
  }
  tape.end();
});
Example #12
Source File: update.js    From ip-index with GNU General Public License v3.0 6 votes vote down vote up
csvAsns = readFileSync(`${__dirname}/../data/asns.csv`).toString()
  .split(/\n/)
  .filter((item) => item.trim().length)
  .map((row) => {
    const items = row.split(',', 3);
    items[0] = +items[0];
    items[2] = items[2].replace('"', '');
    return items;
  })
Example #13
Source File: coreExports.js    From fes.js with MIT License 6 votes vote down vote up
export default function (api) {
    api.onGenerateFiles(async () => {
        const coreExports = await api.applyPlugins({
            key: 'addCoreExports',
            type: api.ApplyPluginsType.add,
            initialValue: []
        });

        const fesExportsHook = {}; // repeated definition
        const absoluteFilePath = 'core/coreExports.js';
        const content = `${coreExports
            .map(item => generateExports(absoluteFilePath, {
                item,
                fesExportsHook
            }))
            .join('\n')}\n`;
        const tpl = readFileSync(join(__dirname, './coreExports.tpl'), 'utf-8');
        api.writeTmpFile({
            path: absoluteFilePath,
            content: tpl.replace('CORE_EXPORTS', content).replace('RUNTIME_PATH', runtimePath)
        });
    });
}
Example #14
Source File: dsv2dsv.js    From cs-wiki with GNU General Public License v3.0 6 votes vote down vote up
options = program
    .version(JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "../package.json"))).version)
    .usage("[options] [file]")
    .option("-o, --out <file>", "output file name; defaults to “-” for stdout", "-")
    .option("-r, --input-delimiter <character>", "input delimiter character", defaultInDelimiter)
    .option("-w, --output-delimiter <character>", "output delimiter character", defaultOutDelimiter)
    .option("--input-encoding <encoding>", "input character encoding; defaults to “utf8”", "utf8")
    .option("--output-encoding <encoding>", "output character encoding; defaults to “utf8”", "utf8")
    .parse(process.argv)
    .opts()
Example #15
Source File: loadDotEnv.js    From fes.js with MIT License 6 votes vote down vote up
/**
 * dotenv wrapper
 * @param envPath string
 */
export default function loadDotEnv(envPath) {
    if (existsSync(envPath)) {
        const parsed = parse(readFileSync(envPath, 'utf-8')) || {};
        Object.keys(parsed).forEach((key) => {
            // eslint-disable-next-line no-prototype-builtins
            process.env[key] = parsed[key];
        });
    }
}
Example #16
Source File: NoiseFilter.js    From inkpaint with MIT License 6 votes vote down vote up
constructor(noise = 0.5, seed = Math.random()) {
    super(
      // vertex shader
      readFileSync(join(__dirname, "../fragments/default.vert"), "utf8"),
      // fragment shader
      readFileSync(join(__dirname, "./noise.frag"), "utf8")
    );

    this.noise = noise;
    this.seed = seed;
  }
Example #17
Source File: modules.js    From Kadena-Mining-Stratum with GNU General Public License v2.0 6 votes vote down vote up
/** Extract information about package.json modules */
function collectModules() {
    var mainPaths = (require.main && require.main.paths) || [];
    var paths = require.cache ? Object.keys(require.cache) : [];
    var infos = {};
    var seen = {};
    paths.forEach(function (path) {
        var dir = path;
        /** Traverse directories upward in the search of package.json file */
        var updir = function () {
            var orig = dir;
            dir = dirname(orig);
            if (!dir || orig === dir || seen[orig]) {
                return undefined;
            }
            if (mainPaths.indexOf(dir) < 0) {
                return updir();
            }
            var pkgfile = join(orig, 'package.json');
            seen[orig] = true;
            if (!existsSync(pkgfile)) {
                return updir();
            }
            try {
                var info = JSON.parse(readFileSync(pkgfile, 'utf8'));
                infos[info.name] = info.version;
            }
            catch (_oO) {
                // no-empty
            }
        };
        updir();
    });
    return infos;
}
Example #18
Source File: lint-versions.js    From rocket with MIT License 6 votes vote down vote up
function readPackageJsonDeps(filePath) {
  if (existsSync(filePath)) {
    const jsonData = JSON.parse(readFileSync(filePath, 'utf-8'));
    const merged = { ...jsonData.dependencies, ...jsonData.devDependencies };
    const result = {};
    Object.keys(merged).forEach(dep => {
      if (merged[dep] && !merged[dep].includes('file:')) {
        result[dep] = merged[dep];
      }
    });
    return result;
  }
  return {};
}
Example #19
Source File: template.js    From bot with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Helper function to render the template
 * @param {string} path - The template path, relative to the project `src/services` directory
 * @param {Object} data - Data you want to pass to the template
 * @return {Promise<string>}
 */
export function renderTemplate(path, data) {
  if (path === null || path === undefined) {
    throw TypeError("Path is required!");
  }

  const templatePath = resolve("src", "services", path);
  const template = readFileSync(templatePath, { encoding: "utf8" });
  return compile(template)(data);
}
Example #20
Source File: filesystem.spec.js    From kit with MIT License 6 votes vote down vote up
suite_copy('replaces strings', () => {
	write('foo.md', 'the quick brown JUMPER jumps over the lazy JUMPEE');
	copy(source_dir, dest_dir, {
		replace: {
			JUMPER: 'fox',
			JUMPEE: 'dog'
		}
	});

	assert.equal(
		readFileSync(join(dest_dir, 'foo.md'), 'utf8'),
		'the quick brown fox jumps over the lazy dog'
	);
});
Example #21
Source File: welcome.js    From HinataMd with GNU General Public License v3.0 6 votes vote down vote up
render = async ({
    wid = '',
    pp = toBase64(readFileSync(join(src, 'avatar_contact.png')), 'image/png'),
    name = '',
    title = '',
    text = '',
    background = toBase64(readFileSync(join(src, 'Aesthetic', 'Aesthetic_000.jpeg')), 'image/jpeg'),
} = {}, format = 'png') => {
    let svg = await genSVG({
        wid, pp, name, text, background, title
    })
    return await toImg(svg, format)
}
Example #22
Source File: index.js    From kit with MIT License 6 votes vote down vote up
function get_netlify_config() {
	if (!existsSync('netlify.toml')) return null;

	try {
		return /** @type {NetlifyConfig} */ (toml.parse(readFileSync('netlify.toml', 'utf-8')));
	} catch (err) {
		err.message = `Error parsing netlify.toml: ${err.message}`;
		throw err;
	}
}
Example #23
Source File: tool-tts.js    From HinataMd with GNU General Public License v3.0 6 votes vote down vote up
function tts(text, lang = 'id') {
  console.log(lang, text)
  return new Promise((resolve, reject) => {
    try {
      let tts = gtts(lang)
      let filePath = join(global.__dirname(import.meta.url), '../tmp', (1 * new Date) + '.wav')
      tts.save(filePath, text, () => {
        resolve(readFileSync(filePath))
        unlinkSync(filePath)
      })
    } catch (e) { reject(e) }
  })
}
Example #24
Source File: index.js    From URT-BOT with MIT License 6 votes vote down vote up
parser = new YargsParser({
    cwd: process.cwd,
    env: () => {
        return env;
    },
    format,
    normalize,
    resolve,
    // TODO: figure  out a  way to combine ESM and CJS coverage, such  that
    // we can exercise all the lines below:
    require: (path) => {
        if (typeof require !== 'undefined') {
            return require(path);
        }
        else if (path.match(/\.json$/)) {
            // Addresses: https://github.com/yargs/yargs/issues/2040
            return JSON.parse(readFileSync(path, 'utf8'));
        }
        else {
            throw Error('only .json config files are supported in ESM');
        }
    }
})
Example #25
Source File: index.js    From aresrpg with MIT License 6 votes vote down vote up
import_query = path => {
  const query = readFileSync(`./src/enjin/graphql/${path}.gql`, 'utf-8')
  return variables =>
    fetch(ENJIN_ENDPOINT, {
      method: 'POST',
      headers,
      body: JSON.stringify({ variables, query }),
    })
      .then(result => result.json())
      .then(({ data, errors }) => {
        if (errors) throw errors
        return data
      })
}
Example #26
Source File: weakCrypto.spec.js    From js-x-ray with MIT License 6 votes vote down vote up
test("it should report a warning in case of `createHash(<weak-algo>)` usage", async(tape) => {
  const fixturesDir = join(FIXTURE_PATH, "directCallExpression");
  const fixtureFiles = await readdir(fixturesDir);

  for (const fixtureFile of fixtureFiles) {
    const fixture = readFileSync(join(fixturesDir, fixtureFile), "utf-8");
    const { warnings: outputWarnings } = runASTAnalysis(fixture);

    const [firstWarning] = outputWarnings;
    tape.strictEqual(outputWarnings.length, 1);
    tape.deepEqual(firstWarning.kind, "weak-crypto");
    tape.strictEqual(firstWarning.value, fixtureFile.split(".").at(0));
    tape.strictEqual(firstWarning.experimental, true);
  }
  tape.end();
});
Example #27
Source File: index.js    From bakabo with GNU General Public License v3.0 6 votes vote down vote up
parser = new YargsParser({
    cwd: process.cwd,
    env: () => {
        return env;
    },
    format,
    normalize,
    resolve,
    // TODO: figure  out a  way to combine ESM and CJS coverage, such  that
    // we can exercise all the lines below:
    require: (path) => {
        if (typeof require !== 'undefined') {
            return require(path);
        }
        else if (path.match(/\.json$/)) {
            return readFileSync(path, 'utf8');
        }
        else {
            throw Error('only .json config files are supported in ESM');
        }
    }
})
Example #28
Source File: parseRequireDeps.js    From fes.js with MIT License 6 votes vote down vote up
function parse(filePath) {
    const content = readFileSync(filePath, 'utf-8');
    return (crequire(content))
        .map(o => o.path)
        .filter(path => path.charAt(0) === '.')
        .map(path => winPath(
            resolve.sync(path, {
                basedir: dirname(filePath),
                extensions: ['.tsx', '.ts', '.jsx', '.js']
            })
        ));
}
Example #29
Source File: obfuscated.spec.js    From js-x-ray with MIT License 6 votes vote down vote up
test("should detect 'jsfuck' obfuscation", (tape) => {
  const trycatch = readFileSync(join(FIXTURE_PATH, "jsfuck.js"), "utf-8");
  const { warnings } = runASTAnalysis(trycatch);

  tape.strictEqual(warnings.length, 1);
  tape.deepEqual(getWarningKind(warnings), ["obfuscated-code"].sort());
  tape.strictEqual(warnings[0].value, "jsfuck");
  tape.end();
});