本文整理匯總了TypeScript中fs-extra.readJSON函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript readJSON函數的具體用法?TypeScript readJSON怎麽用?TypeScript readJSON使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了readJSON函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: async
const migrateV6Plugins = async () => {
if (!await fs.pathExists(pluginsDir)) return
process.stderr.write('heroku: migrating plugins\n')
try {
const p = path.join(pluginsDir, 'user.json')
if (await fs.pathExists(p)) {
const {manifest} = await fs.readJSON(p)
for (let plugin of Object.keys(manifest.plugins)) {
process.stderr.write(`heroku-cli: migrating ${plugin}\n`)
await exec('heroku', ['plugins:install', plugin])
}
}
} catch (err) {
this.warn(err)
}
try {
const p = path.join(pluginsDir, 'link.json')
if (await fs.pathExists(p)) {
const {manifest} = await fs.readJSON(path.join(pluginsDir, 'link.json'))
for (let {root} of Object.values(manifest.plugins) as any) {
process.stderr.write(`heroku-cli: migrating ${root}\n`)
await exec('heroku', ['plugins:link', root])
}
}
} catch (err) {
this.warn(err)
}
await fs.remove(pluginsDir)
process.stderr.write('heroku: done migrating plugins\n')
}
示例2: writeTestingPackageJson
/**
* For a given repo, generate a new package.json and write it to disk. This
* is a testing-specific package.json manifest, which means that it will
* include local references to dependencies that were also converted in the
* workspace.
*/
async function writeTestingPackageJson(
repo: WorkspaceRepo,
localConversionMap: Map<string, string>,
options: WorkspaceTestSettings) {
const bowerPackageName = path.basename(repo.dir);
const bowerJsonPath = path.join(repo.dir, 'bower.json');
const bowerJson = await fse.readJSON(bowerJsonPath);
const npmPackageName =
lookupNpmPackageName(bowerJsonPath) || bowerPackageName;
const packageJsonPath = path.join(repo.dir, 'package.json');
const existingPackageJson =
await readJsonIfExists<Partial<YarnConfig>>(packageJsonPath);
const packageJson = generatePackageJson(
bowerJson,
{
name: npmPackageName,
version: options.packageVersion,
flat: options.flat,
private: options.private,
},
localConversionMap,
existingPackageJson);
writeJson(packageJson, packageJsonPath);
}
示例3:
export async function readJsonIfExists<T>(filepath: string):
Promise<T|undefined> {
if (await fse.pathExists(filepath)) {
return await fse.readJSON(filepath) as T;
}
return undefined;
}
示例4: initializeFromJsonFile
export async function initializeFromJsonFile(jsonFilepath: string, debug?: boolean): Promise<void> {
if (!await fse.pathExists(jsonFilepath)) {
throw new Error(`The Json file '${jsonFilepath}' does not exist.`);
}
const { publisher, name, version, aiKey } = await fse.readJSON(jsonFilepath);
initialize(`${publisher}.${name}`, version, aiKey, !!debug);
}
示例5: initilizeFromJsonFile
export async function initilizeFromJsonFile(fsPath: string): Promise<void> {
if (await fse.pathExists(fsPath)) {
const { publisher, name, version, aiKey } = await fse.readJSON(fsPath);
initilize(publisher, name, version, aiKey);
} else {
throw new Error(`The Json file '${fsPath}' does not exist.`);
}
}
示例6: prepareHTML
export function prepareHTML(param: IPrepareHTMLOptions): Promise<string> {
const filter = moveTo(param.target);
return Promise.all([
readFile(join(__dirname, '../src/index.html'), 'utf8'),
readJSON(join(__dirname, '../package.json')),
readJSON(join(__dirname, './meta.json'))
])
.then((data) => {
const [file, pack, meta] = data;
const connectionTypes = ['mainnet', 'testnet'];
if (!param.scripts) {
const sourceFiles = getFilesFrom(join(__dirname, '../src'), '.js', function (name, path) {
return !name.includes('.spec') && !path.includes('/test/');
});
param.scripts = meta.vendors.map((i) => join(__dirname, '..', i)).concat(sourceFiles);
param.scripts.push(join(__dirname, '../loginDaemon.js'));
}
if (!param.styles) {
param.styles = meta.stylesheets.map((i) => join(__dirname, '..', i)).concat(getFilesFrom(join(__dirname, '../src'), '.less'));
}
const networks = connectionTypes.reduce((result, item) => {
result[item] = meta.configurations[item];
return result;
}, Object.create(null));
return compile(file)({
pack: pack,
domain: meta.domain,
build: {
type: 'web'
},
network: networks[param.connection]
});
})
.then((file) => {
return replaceStyles(file, param.styles.map(filter).map(s => `/${s}`));
}).then((file) => {
return replaceScripts(file, param.scripts.map(filter));
});
}
示例7: async
read: async () => {
const [data, stat] = await Promise.all([fs.readJSON(filepath), fs.stat(filepath)]);
// Throw an error instead of returning stale data if the file has expired
if (Date.now() - stat.mtimeMs > expiryInMin * 60 * 1000) {
throw new CacheExpiredError('Cache expired', filepath, stat.mtimeMs);
}
return data;
},
示例8: fetchCache
export async function fetchCache(cachePath: string, cacheDuration: number, options: any): Promise<Array<string>> {
let cachePresent = fs.existsSync(cachePath)
if (cachePresent && !_isStale(cachePath, cacheDuration)) {
return fs.readJSON(cachePath)
}
const cache = await options.cacheFn()
// TODO: move this to a fork
await updateCache(cachePath, cache)
return cache
}
示例9: getBuildParams
export async function getBuildParams(param: IPrepareHTMLOptions) {
const [pack, meta, themesConf] = await Promise.all([
readJSON(join(__dirname, '../package.json')) as Promise<IPackageJSON>,
readJSON(join(__dirname, './meta.json')) as Promise<IMetaJSON>,
readJSON(join(__dirname, '../src/themeConfig/theme.json'))
]);
const { themes } = themesConf;
const { domain, analyticsIframe } = meta as any;
const { connection, type, buildType, outerScripts = [] } = param;
const config = meta.configurations[connection];
const networks = ['mainnet', 'testnet'].reduce((result, connection) => {
result[connection] = meta.configurations[connection];
return result;
}, Object.create(null));
const scripts = getScripts(param, pack, meta).concat(outerScripts);
const styles = getStyles(param, meta, themes);
const isWeb = type === 'web';
const isProduction = buildType && buildType === 'min';
const matcherPriorityList = connection === 'mainnet' ? MAINNET_DATA : TESTNET_DATA;
const { origin, oracle, feeConfigUrl, bankRecipient } = config;
return {
pack,
isWeb,
origin,
analyticsIframe,
oracle,
domain,
styles,
scripts,
isProduction,
feeConfigUrl,
bankRecipient,
build: { type },
matcherPriorityList,
network: networks[connection],
themesConf: themesConf,
langList: meta.langList,
};
}
示例10: Ajv
export function validate<T>(data: T, schemaName: string): Promise<T> {
const respath = path.join(path.dirname(__dirname), "res");
return fs.readJSON(path.join(respath, schemaName + ".json")).then(function (schema) {
const ajv = new Ajv({ schemaId: 'auto', allErrors: true });
const metaschema = require('ajv/lib/refs/json-schema-draft-04.json');
ajv.addMetaSchema(metaschema);
if (!ajv.validate(schema, data)) {
throw ("JSON schema errors: " + JSON.stringify(ajv.errors, null, 2));
}
return data;
})
}
示例11: get_railroad
/** get_railroad loads the current railroad from the resources. */
function get_railroad(): Promise<IRailRoadImplem> {
const filePath = path.join(RES_FOLDER, "railroad.json");
return (fs.readJSON(filePath, { encoding: "UTF-8" }) as Promise<IRailRoadImplem>).then(
data => validate(data, "IRailRoad").then(function(data) {
for(let i=0; i< data.occupancy.length; i++) {
data.occupancy[i].id = i;
}
return data;
})
).catch(
err => (console.log("Cannot proceed without railroad description file: " + err), process.exit(1)));
}
示例12: async
return async (...args: any[]): Promise<any> => {
let f = path.join(cacheDir, `${key}.json`)
try {
let fi = await fs.stat(f)
if (fi && minutesAgo(20) < fi.mtime) {
return await fs.readJSON(f)
}
} catch (err) {
debug(err)
submitError(err)
await fs.remove(f)
}
let body = await fn(...args)
await fs.outputJSON(f, body)
return body
}
示例13: read
/**
* parse manifest
* @returns {Promise<void>}
*/
async read() {
const zip = new Node7z()
await zip.extractFull(this.filename, this.tempDir)
const manifestFile = path.join(this.tempDir, 'modpack.json')
if (!await fs.pathExists(manifestFile)) {
throw new Error('invalid modpack: modpack.json not found')
}
const manifest = await fs.readJSON(manifestFile)
const validatorResult = validate(manifest, ModpackManifestSchema)
if (!validatorResult.valid) {
let err = new Error('invalid modpack: modpack.json format error')
err['validate'] = validatorResult.errors
throw err
}
this.manifest = manifest
}
示例14: read_locomotive
/** Reads a locomotive description file
* @param locoPath path to a folder containing a locomotive description.
* @return a promise of locomotive description object.
*/
function read_locomotive(locoPath: string): Promise<ILocomotive> {
const locoFile = path.join(locoPath, "loco.json");
return (fs.readJSON(locoFile, { encoding: "UTF-8" }) as Promise<ILocomotive>).then(
data => validate(data, "ILocomotive")
).then (
function (loco) {
const locoImgFile = path.join(locoPath, "image.jpg");
if (loco.image) { return loco; }
return fs.pathExists(locoImgFile).then(
function (existsImage) {
console.log(locoImgFile + " => " + existsImage);
if (existsImage) {
loco.image = locoImgFile;
} else {
loco.image = path.join(path.dirname(__dirname), "res/loco.jpg");
}
return loco;
});
}).catch(
function (err) { throw ("(" + locoPath + "): " + err); }
);
}
示例15: convert
/**
* Convert a package-layout project to JavaScript modules & npm.
*/
export default async function convert(options: PackageConversionSettings) {
const outDir = options.outDir;
const npmPackageName = options.packageName;
await setupOutDir(outDir, options.cleanOutDir);
// Configure the analyzer and run an analysis of the package.
const bowerJson =
await fse.readJSON(path.join(options.inDir, 'bower.json')) as
Partial<BowerConfig>;
const bowerPackageName = bowerJson.name!;
const analyzer = configureAnalyzer(options);
const analysis = await analyzer.analyzePackage();
await setupOutDir(options.outDir, !!options.cleanOutDir);
// Create the url handler & converter.
const urlHandler = new PackageUrlHandler(
analyzer,
bowerPackageName,
npmPackageName,
options.packageType,
options.inDir);
const conversionSettings = createDefaultConversionSettings(analysis, options);
const converter =
new ProjectConverter(analysis, urlHandler, conversionSettings);
// Convert the package
await converter.convertPackage(bowerPackageName);
// Filter out external results before writing them to disk.
const results = converter.getResults();
for (const [newPath] of results) {
if (!PackageUrlHandler.isUrlInternalToPackage(newPath)) {
results.delete(newPath);
}
}
await writeFileResults(outDir, results);
// transform travis config
await transformTravisConfig(options.inDir, options.outDir);
// add `node_modules` to gitignore
const gitIgnoreFile = path.join(options.inDir, '.gitignore');
await ignoreNodeModules(gitIgnoreFile);
const packageJsonPath = path.join(options.inDir, 'package.json');
const existingPackageJson =
await readJsonIfExists<Partial<YarnConfig>>(packageJsonPath);
// Generate a new package.json, and write it to disk.
const packageJson = generatePackageJson(
bowerJson,
{
name: options.packageName,
version: options.packageVersion,
flat: options.flat,
private: options.private,
},
undefined,
existingPackageJson);
writeJson(packageJson, packageJsonPath);
// Delete files that were explicitly requested to be deleted.
if (options.deleteFiles !== undefined) {
await deleteGlobsSafe(options.deleteFiles, outDir);
}
// TODO(fks): create a new manifest.json, and write it to disk.
// Currently blocked by the fact that package-url-handler treats all
// dependencies as local/internal.
}