fs-extra#writeJSON TypeScript Examples
The following examples show how to use
fs-extra#writeJSON.
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: executor.ts From nx-plugins with MIT License | 6 votes |
async function caretDepsVersion(normalizedOptions: PublishExecutorNormalizedSchema) {
const pkgJsonPath = joinPathFragments(normalizedOptions.pkgLocation, 'package.json');
const packageJson = await readJson(pkgJsonPath);
const projectsNames = await getAllProjectsNames();
projectsNames.forEach((name) => {
if (name in (packageJson.peerDependencies || {})) {
packageJson.peerDependencies[name] = addCaret(packageJson.peerDependencies[name]);
}
if (name in (packageJson.dependencies || {})) {
packageJson.dependencies[name] = addCaret(packageJson.dependencies[name]);
}
});
await writeJson(pkgJsonPath, packageJson, { spaces: 2 });
}
Example #2
Source File: ui5-model.ts From ui5-language-assistant with Apache License 2.0 | 6 votes |
async function writeToCache(
filePath: string | undefined,
apiJson: unknown
): Promise<void> {
if (filePath !== undefined) {
try {
await writeJson(filePath, apiJson);
} catch (err) {
getLogger().warn("Could not write cache file For UI5 lib", {
filePath,
error: err,
});
}
}
}
Example #3
Source File: executor.ts From nx-plugins with MIT License | 6 votes |
async function syncDepsVersion(normalizedOptions: PublishExecutorNormalizedSchema) {
const pkgJsonPath = joinPathFragments(normalizedOptions.pkgLocation, 'package.json');
const packageJson = await readJson(pkgJsonPath);
const projectsNames = await getAllProjectsNames();
const version = packageJson.version;
projectsNames.forEach((name) => {
if (name in (packageJson.peerDependencies || {})) {
packageJson.peerDependencies[name] = version;
}
if (name in (packageJson.dependencies || {})) {
packageJson.dependencies[name] = version;
}
});
await writeJson(pkgJsonPath, packageJson, { spaces: 2 });
}
Example #4
Source File: WikiVuepressIntegrated.ts From joplin-blog with MIT License | 6 votes |
async init() {
await this.resourceWriter.clean()
const sidebarConfigPath = path.resolve(
this.config.rootPath,
'.vuepress/sidebar.json',
)
await mkdirp(path.resolve(this.config.rootPath, 'p/resource'))
await mkdirp(path.dirname(sidebarConfigPath))
await writeJson(sidebarConfigPath, await this.buildSidebar(), {
spaces: 2,
})
}
Example #5
Source File: convert.test.ts From joplin-utils with MIT License | 6 votes |
async function migrate2To3(dirs: string[]) {
await AsyncArray.forEach(dirs, async (dir) => {
await AsyncArray.map(await readdir(path.resolve(dir)), async (file) => {
const jsonPath = path.resolve(dir, file as string)
await writeJson(jsonPath, flatObject(await readJson(jsonPath)), {
spaces: 2,
})
})
})
await new GeneratorCommandProgram().main({
dirs,
language: 'en',
watch: false,
})
}
Example #6
Source File: login.ts From cli with Apache License 2.0 | 6 votes |
export async function loginWithApiKey(
apiKey: string,
orgId: string,
env: string
) {
if (!existsSync(getConfigFilePath())) {
throw 'Missing config file';
}
const cfg = await readJSON(getConfigFilePath());
cfg.accessToken = apiKey;
cfg.organization = orgId;
cfg.environment = env;
cfg.analyticsEnabled = false;
cfg.anonymous = true;
await writeJSON(getConfigFilePath(), cfg);
}
Example #7
Source File: Exporter.ts From joplin-utils with MIT License | 6 votes |
async writeConfig(config: ExportConfig) {
const configPath = path.resolve(this.config.rootPath, 'config')
await mkdirp(configPath)
await AsyncArray.forEach(Object.entries(config), async ([fileName, v]) => {
await writeJson(path.resolve(configPath, fileName + '.json'), v, {
spaces: 2,
})
})
}
Example #8
Source File: TagUseService.ts From joplin-utils with MIT License | 6 votes |
async save(tags: Pick<TagGetRes, 'id' | 'title'>[]) {
await this.init()
const db = await readJson(this.configPath)
const map = await this.getMap()
tags.forEach((tag) => {
map.set(tag.id, {
id: tag.id,
title: tag.title,
lastUseTime: Date.now(),
} as TagUseEntity)
})
await writeJson(this.configPath, {
...db,
tagUse: [...map.values()],
})
}
Example #9
Source File: CliProgram.ts From joplin-utils with MIT License | 6 votes |
async generate(name: string): Promise<void> {
const destPath = path.resolve(this.config.basePath, name)
await copy(
path.resolve(__dirname, '../templates/joplin-plugin-template'),
destPath,
)
await move(
path.resolve(destPath, '_.gitignore'),
path.resolve(destPath, '.gitignore'),
)
const pkgPath = path.resolve(destPath, 'package.json')
await writeJson(
pkgPath,
{
...(await readJson(pkgPath)),
name,
},
{
spaces: 2,
},
)
}
Example #10
Source File: update.ts From malagu with MIT License | 6 votes |
async function updatePackage(version: string, skipIntallingComponent?: boolean) {
const packagePath = join(process.cwd(), 'package.json');
if (existsSync(packagePath)) {
const projectPkg = await readJSON(packagePath);
const dependencies = projectPkg.dependencies ?? {};
const devDependencies = projectPkg.devDependencies ?? {};
for (const name of Object.keys(dependencies)) {
if (name.startsWith('@malagu/')) {
dependencies[name] = version;
}
}
for (const name of Object.keys(devDependencies)) {
if (name.startsWith('@malagu/')) {
devDependencies[name] = version;
}
}
await writeJSON(packagePath, projectPkg, { spaces: 2 });
if (skipIntallingComponent) {
await getPackager().install();
}
}
}
Example #11
Source File: index.ts From cli with MIT License | 5 votes |
async copyFile() {
this.core.cli.log('Copy Files to build directory...');
// copy packages config files
const packageObj: any = this.core.service.package || {};
if (this.core.config.specFile.path) {
// backup original yml file
await copy(
this.core.config.specFile.path,
resolve(this.midwayBuildPath, './f.origin.yml')
);
this.core.cli.log(
` - Copy ${this.core.config.specFile.path.replace(
`${this.servicePath}/`,
''
)} to ${'f.origin.yml'}`
);
}
const exclude = [].concat(packageObj.exclude || []);
if (!packageObj.lockFile) {
exclude.push('yarn.lock');
exclude.push('package-lock.json');
exclude.push('pnpm-lock.yaml');
}
await copyFiles({
sourceDir: this.servicePath,
targetDir: this.midwayBuildPath,
include: this.options.skipBuild
? [].concat(packageObj.include || [])
: [this.options.sourceDir || 'src'].concat(packageObj.include || []),
exclude,
log: path => {
this.core.cli.log(` - Copy ${path}`);
},
});
if (this.options.skipBuild) {
// 跳过编译时也不处理package.json
return;
}
if (this.codeAnalyzeResult.integrationProject) {
let originPkgJson = {};
try {
const pkgJsonPath = join(this.servicePath, 'package.json');
if (existsSync(pkgJsonPath)) {
originPkgJson = JSON.parse(readFileSync(pkgJsonPath).toString());
}
} catch {
//
}
await writeJSON(join(this.midwayBuildPath, 'package.json'), {
...originPkgJson,
name: this.codeAnalyzeResult.projectType,
version: '1.0.0',
dependencies: this.codeAnalyzeResult.usingDependenciesVersion.valid,
});
}
if (this.options.sharedDir) {
this.options.sharedTargetDir = this.options.sharedTargetDir || 'static';
this.core.cli.log(
` - Copy Shared Files to build directory(${this.options.sharedTargetDir})...`
);
this.options.sharedDir = this.transformToAbsolute(
this.servicePath,
this.options.sharedDir
);
this.options.sharedTargetDir = this.transformToAbsolute(
this.midwayBuildPath,
this.options.sharedTargetDir
);
console.log(this.options.sharedTargetDir);
await copy(this.options.sharedDir, this.options.sharedTargetDir);
}
this.core.cli.log(' - File copy complete');
}
Example #12
Source File: login.ts From cli with Apache License 2.0 | 5 votes |
export async function clearAccessTokenFromConfig() {
if (!existsSync(getConfigFilePath())) {
return;
}
const cfg = await readJSON(getConfigFilePath());
delete cfg.accessToken;
await writeJSON(getConfigFilePath(), cfg);
}
Example #13
Source File: npm.ts From malagu with MIT License | 5 votes |
writeLockfile(lockfilePath: string, content: any) {
return writeJSON(lockfilePath, content, { spaces: 2 });
}
Example #14
Source File: init-manager.ts From malagu with MIT License | 5 votes |
async render(): Promise<void> {
const packageJsonPath = resolve(this.outputDir, 'package.json');
if (existsSync(packageJsonPath)) {
const packageJson = await readJSON(packageJsonPath, { encoding: 'utf8' });
packageJson.name = basename(this.outputDir);
await writeJSON(packageJsonPath, packageJson, { encoding: 'utf8', spaces: 2 });
}
}
Example #15
Source File: TagUseService.ts From joplin-utils with MIT License | 5 votes |
private async init() {
if (!(await pathExists(this.configPath))) {
await mkdirp(path.dirname(this.configPath))
await writeJson(this.configPath, {
tagUse: [],
})
}
}
Example #16
Source File: WikiVuepressIntegrated.ts From joplin-utils with MIT License | 5 votes |
async init() {
const sidebarConfigPath = path.resolve(this.config.rootPath, '.vuepress/sidebar.json')
await mkdirp(path.dirname(sidebarConfigPath))
await writeJson(sidebarConfigPath, await this.buildSidebar(), {
spaces: 2,
})
}
Example #17
Source File: CacheCommander.ts From joplin-utils with MIT License | 5 votes |
async write(cache: CacheConfig) {
await writeJson(this.cachePath, cache)
}
Example #18
Source File: npm.ts From DefinitelyTyped-tools with MIT License | 5 votes |
export async function withNpmCache<T>(
uncachedClient: UncachedNpmInfoClient,
cb: (client: CachedNpmInfoClient) => Promise<T>,
cacheDir = defaultCacheDir
): Promise<T> {
const log = loggerWithErrors()[0];
const cacheFile = joinPaths(cacheDir, cacheFileBasename);
let unroll: Map<string, NpmInfo>;
log.info(`Checking for cache file at ${cacheFile}...`);
const cacheFileExists = await pathExists(cacheFile);
if (cacheFileExists) {
log.info("Reading cache file...");
const cachedJson = (await readJson(cacheFile)) as Record<string, NpmInfoRaw>;
log.info(`Cache file ${cacheFile} exists, copying to map...`);
unroll = recordToMap(cachedJson, npmInfoFromJson);
} else {
log.info("Cache file doesn't exist, using empty map.");
unroll = new Map();
}
const res = await cb({ getNpmInfoFromCache, fetchAndCacheNpmInfo });
log.info("Writing npm cache.");
await ensureFile(cacheFile);
await writeJson(cacheFile, mapToRecord(unroll, jsonFromNpmInfo));
return res;
/** May return old info -- caller should check that this looks up-to-date. */
function getNpmInfoFromCache(escapedPackageName: string): NpmInfo | undefined {
return unroll.get(escapedPackageName);
}
/** Call this when the result of getNpmInfoFromCache looks potentially out-of-date. */
async function fetchAndCacheNpmInfo(escapedPackageName: string): Promise<NpmInfo | undefined> {
const info = await uncachedClient.fetchNpmInfo(escapedPackageName);
if (info) {
unroll.set(escapedPackageName, info);
}
return info;
}
}
Example #19
Source File: remixd.ts From remix-project with MIT License | 4 votes |
(async () => {
const { version } = require('../../package.json') // eslint-disable-line
program.version(version, '-v, --version')
program
.description('Establish a two-way websocket connection between the local computer and Remix IDE for a folder')
.option('-u, --remix-ide <url>', 'URL of remix instance allowed to connect')
.option('-s, --shared-folder <path>', 'Folder to share with Remix IDE (Default: CWD)')
.option('-r, --read-only', 'Treat shared folder as read-only (experimental)')
.on('--help', function () {
console.log('\nExample:\n\n remixd -s ./shared_project -u http://localhost:8080')
}).parse(process.argv)
// eslint-disable-next-line
await warnLatestVersion()
if (!program.remixIde) {
console.log('\x1b[33m%s\x1b[0m', '[WARN] You can only connect to remixd from one of the supported origins.')
} else {
const isValid = await isValidOrigin(program.remixIde)
/* Allow unsupported origins and display warning. */
if (!isValid) {
console.log('\x1b[33m%s\x1b[0m', '[WARN] You are using IDE from an unsupported origin.')
console.log('\x1b[33m%s\x1b[0m', 'Check https://gist.github.com/EthereumRemix/091ccc57986452bbb33f57abfb13d173 for list of all supported origins.\n')
// return
}
console.log('\x1b[33m%s\x1b[0m', '[WARN] You may now only use IDE at ' + program.remixIde + ' to connect to that instance')
}
if (!program.sharedFolder) program.sharedFolder = process.cwd() // if no specified, use the current folder
if (program.sharedFolder && existsSync(absolutePath('./', program.sharedFolder))) {
console.log('\x1b[33m%s\x1b[0m', '[WARN] Any application that runs on your computer can potentially read from and write to all files in the directory.')
console.log('\x1b[33m%s\x1b[0m', '[WARN] Symbolic links are not forwarded to Remix IDE\n')
try {
startService('folder', (ws: WS, sharedFolderClient: servicesList.Sharedfolder, error: any) => {
if (error) {
errorHandler(error, 'hardhat')
return false
}
sharedFolderClient.setWebSocket(ws)
sharedFolderClient.setupNotifications(program.sharedFolder)
sharedFolderClient.sharedFolder(program.sharedFolder)
})
startService('slither', (ws: WS, sharedFolderClient: servicesList.Sharedfolder) => {
sharedFolderClient.setWebSocket(ws)
sharedFolderClient.sharedFolder(program.sharedFolder)
})
// Run truffle service if a truffle project is shared as folder
const truffleConfigFilePath = absolutePath('./', program.sharedFolder) + '/truffle-config.js'
if (existsSync(truffleConfigFilePath)) {
startService('truffle', (ws: WS, sharedFolderClient: servicesList.Sharedfolder, error: any) => {
if (error) {
errorHandler(error, 'truffle')
return false
}
sharedFolderClient.setWebSocket(ws)
sharedFolderClient.sharedFolder(program.sharedFolder)
})
}
// Run hardhat service if a hardhat project is shared as folder
const hardhatConfigFilePath = absolutePath('./', program.sharedFolder)
const isHardhatProject = existsSync(hardhatConfigFilePath + '/hardhat.config.js') || existsSync(hardhatConfigFilePath + '/hardhat.config.ts')
if (isHardhatProject) {
startService('hardhat', (ws: WS, sharedFolderClient: servicesList.Sharedfolder, error: Error) => {
if (error) {
errorHandler(error, 'hardhat')
return false
}
sharedFolderClient.setWebSocket(ws)
sharedFolderClient.sharedFolder(program.sharedFolder)
})
}
/*
startService('git', (ws: WS, sharedFolderClient: servicesList.Sharedfolder) => {
sharedFolderClient.setWebSocket(ws)
sharedFolderClient.sharedFolder(program.sharedFolder)
})
*/
} catch (error) {
throw new Error(error)
}
} else {
console.log('\x1b[31m%s\x1b[0m', '[ERR] No valid shared folder provided.')
}
// kill
function kill () {
for (const k in killCallBack) {
try {
killCallBack[k]()
} catch (e) {
console.log(e)
}
}
process.exit(0)
}
process.on('SIGINT', kill) // catch ctrl-c
process.on('SIGTERM', kill) // catch kill
process.on('exit', kill)
async function isValidOrigin (origin: string): Promise<any> {
if (!origin) return false
const domain = getDomain(origin)
const gistUrl = 'https://gist.githubusercontent.com/EthereumRemix/091ccc57986452bbb33f57abfb13d173/raw/3367e019335746b73288e3710af2922d4c8ef5a3/origins.json'
try {
const { data } = (await Axios.get(gistUrl)) as { data: any }
try {
await writeJSON(path.resolve(path.join(__dirname, '../..', 'origins.json')), { data })
} catch (e) {
console.error(e)
}
const dataArray:string[] = data
return dataArray.includes(origin) ? dataArray.includes(origin) : dataArray.includes(domain)
} catch (e) {
try {
// eslint-disable-next-line
const origins = require('../../origins.json')
const { data } = origins
return data.includes(origin) ? data.includes(origin) : data.includes(domain)
} catch (e) {
return false
}
}
}
})()