How to use the fs-extra.readJson function in fs-extra

To help you get started, we’ve selected a few fs-extra 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 unfoldingWord / translationCore / src / js / helpers / ToolsMetadataHelpers.js View on Github external
const fillDefaultTools = (moduleFilePathList) => {
  let tempMetadatas = [];

  // This makes sure we're done with all the files first before we call the callback
  for (let filePath of moduleFilePathList) {
    fs.readJson(filePath, (error, metadata) => {
      if (error) {
        console.error(error);
      } else {
        metadata.folderName = path.dirname(filePath);
        metadata.imagePath = path.resolve(filePath, '../icon.png');
        metadata.badgeImagePath = path.resolve(filePath, '../badge.png');
        tempMetadatas.push(metadata);
      }
    });
  }
  return tempMetadatas;
};
github jariz / gatsby-plugin-s3 / src / bin.ts View on Github external
const deploy = async ({ yes, bucket }: { yes: boolean, bucket: string }) => {
    const spinner = ora({ text: 'Retrieving bucket info...', color: 'magenta' }).start();

    const uploadQueue: Array> = [];

    try {
        const config: PluginOptions = await readJson(CACHE_FILES.config);
        const params: Params = await readJson(CACHE_FILES.params);
        const routingRules: RoutingRules = await readJson(CACHE_FILES.routingRules);
        const redirectObjects: GatsbyRedirect[] = fs.existsSync(CACHE_FILES.redirectObjects)
            ? await readJson(CACHE_FILES.redirectObjects)
            : [];

        // Override the bucket name if it is set via command line
        if (bucket) {
            config.bucketName = bucket;
        }

        const s3 = new S3({
            region: config.region,
            endpoint: config.customAwsEndpointHostname,
        });

        const { exists, region } = await getBucketInfo(config, s3);
github Fiddlekins / podbot / js / postProcess.js View on Github external
async function getConfig() {
	try {
		const config = await fs.readJson(configPath);
		makeRelativePathsAbsolute(config);
		return config;
	} catch (err) {
		// Don't care about err, it just means there isn't a valid config file available
		// Return a bunch of defaults instead
		return {
			podbot: {
				podcastPath: path.join(__dirname, '..', 'podcasts')
			}
		};
	}
}
github nuxt / now-builder / src / typescript.ts View on Github external
export async function prepareTypescriptEnvironment ({ pkg, spawnOpts, rootDir }: PrepareTypescriptOptions): Promise {
  spawnOpts = { ...spawnOpts, env: { ...spawnOpts.env, NODE_PRESERVE_SYMLINKS: '1' } }

  if ((fs.existsSync('tsconfig.json'))) {
    let tsConfig
    try {
      tsConfig = await fs.readJson('tsconfig.json')
    } catch (e) {
      throw new Error(`Can not read tsconfig.json from ${rootDir}`)
    }
    tsConfig.exclude = [...(tsConfig.exclude || []), 'node_modules_dev', 'node_modules_prod']
    await fs.writeJSON('tsconfig.json', tsConfig)
  }

  //   Edit dependencies
  if (pkg.dependencies && Object.keys(pkg.dependencies).includes('@nuxt/typescript-runtime')) {
    delete pkg.dependencies['@nuxt/typescript-runtime']
  }
}
github strongloop / loopback-workspace / test / acceptance / use-cases / test-scripts / create-model-property.js View on Github external
this.Then(/^the model property is created$/, function(next) {
    const testsuite = this;
    const model = this.getWorkspace(templateName).model(modelId);
    const file = model.getFilePath();
    fs.readJson(file, function(err, data) {
      if (err) return next(err);
      const property = data &&
        data.properties &&
        data.properties[PropertyName];
      testsuite.expect(property).to.not.to.be.undefined();
      testsuite.expect({type: propertyDef.type}).to.eql(property);
      next();
    });
  });
};
github vtex / toolbelt / src / modules / rewriter / export.ts View on Github external
const handleExport = async (csvPath: string) => {
  const rawRoutesIndexFiles = await rewriter.routesIndexFiles()
  if (!rawRoutesIndexFiles) {
    log.info('No data to be exported.')
    return
  }
  const routesIndexFiles = prop('routeIndexFiles', rawRoutesIndexFiles)
  const indexHash = await createHash('md5')
    .update(`${account}_${workspace}_${JSON.stringify(rawRoutesIndexFiles)}`)
    .digest('hex')
  const numberOfFiles = sum(compose(map(Number), pluck('fileSize'))(routesIndexFiles))
  if (numberOfFiles === 0) {
    log.info('No data to be exported.')
    return
  }
  const metainfo = await readJson(METAINFO_FILE).catch(() => ({}))
  const exportMetainfo = metainfo[EXPORTS] || {}
  const listOfRanges = generateListOfRanges(numberOfFiles)
  let counter = exportMetainfo[indexHash] ? exportMetainfo[indexHash].counter : 0
  let listOfRoutes = exportMetainfo[indexHash] ? exportMetainfo[indexHash].data : []

  const bar = progressBar('Exporting routes...', counter, length(listOfRanges))

  const listener = createInterface({ input: process.stdin, output: process.stdout }).on('SIGINT', () => {
    saveMetainfo(metainfo, EXPORTS, indexHash, counter, listOfRoutes)
    console.log('\n')
    process.exit()
  })

  await Promise.each(listOfRanges.splice(counter), async ([from, to]) => {
    let result: any
    try {
github ryanelian / instapack / bin / index.js View on Github external
return __awaiter(this, void 0, void 0, function* () {
            const templateFolder = upath.join(__dirname, '../templates', template);
            const exist = yield fse.pathExists(templateFolder);
            if (!exist) {
                Shout_1.Shout.error('Unable to find new project template for:', chalk.cyan(template));
                return;
            }
            let mergedPackageJson;
            const projectPackageJsonPath = upath.join(this.projectFolder, 'package.json');
            const templatePackageJsonPath = upath.join(templateFolder, 'package.json');
            if ((yield fse.pathExists(projectPackageJsonPath)) && (yield fse.pathExists(templatePackageJsonPath))) {
                const projectPackageJson = yield fse.readJson(projectPackageJsonPath);
                const templatePackageJson = yield fse.readJson(templatePackageJsonPath);
                mergedPackageJson = MergePackageJson_1.mergePackageJson(projectPackageJson, templatePackageJson);
            }
            console.log('Initializing new project using template:', chalk.cyan(template));
            console.log('Scaffolding project into your web app...');
            yield fse.copy(templateFolder, this.projectFolder);
            if (mergedPackageJson) {
                console.log(`Merging ${chalk.blue('package.json')}...`);
                yield fse.writeJson(projectPackageJsonPath, mergedPackageJson, {
                    spaces: 2
                });
            }
            console.log(chalk.green('Scaffold completed.'), 'To build the app, type:', chalk.yellow('ipack'));
        });
    }
github sakuli / sakuli / scripts / distribute-npm-scripts.js View on Github external
.forEach(async ([packageName, sharedPackageJson]) => {
                const _sharedScripts = {...sharedScripts};
                const pkgJson = await readJson(sharedPackageJson);
                if (pkgJson && pkgJson.name.startsWith('@sakuli')) {

                    Object.keys(_sharedScripts).forEach(scriptKey => {
                        _sharedScripts[scriptKey] = `${_sharedScripts[scriptKey]}`
                            .replace(/\{package\}/g, packageName)
                    })
                    const newPackageJson = {
                        ...pkgJson,
                        scripts: {
                            ...pkgJson.scripts,
                            ..._sharedScripts
                        }
                    }
                    console.log('Would write to ' + sharedPackageJson);
                    console.log(JSON.stringify(_sharedScripts, null, 2))
                    await writeJson(sharedPackageJson, newPackageJson, {
github atomist / sdm-core / lib / internal / preferences / FilePreferenceStore.ts View on Github external
private async read(): Promise {
        return (await fs.readJson(this.filePath)) as PreferenceFile;
    }
github ryanelian / instapack / src / CopyBuildTool.ts View on Github external
async build(): Promise {
        const packageJson = await fse.readJson(this.pathFinder.packageJson);
        const dependencies = new Set();
        if (packageJson.dependencies) {
            for (const dependency in packageJson.dependencies) {
                dependencies.add(dependency);
            }
        }
        if (packageJson.devDependencies) {
            for (const dependency in packageJson.devDependencies) {
                dependencies.add(dependency);
            }
        }

        const copyTasks: Promise[] = [];
        for (const job of this.variables.copy) {
            if (dependencies.has(job.library)) {
                copyTasks.push(this.tryCopy(job, false));