fs#mkdirSync TypeScript Examples

The following examples show how to use fs#mkdirSync. 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: utils.ts    From squid with GNU General Public License v3.0 7 votes vote down vote up
export function normalizeDefaults(): void {
    if (!existsSync(configFilePath)) {
        if (!existsSync(configDirectory)) {
            mkdirSync(configDirectory);
        }
        writeDefaultConfigData();
        return;
    }
    let config;
    try {
        config = JSON.parse(readFileSync(configFilePath, 'utf8'));
    } catch (e) {
        writeDefaultConfigData();
    }
}
Example #2
Source File: artifact.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Write the ABI and bytecode for the contract `contractName` to the ABI and bytecode files.
 */
function writeContractArtifact(task: Task, contractName: string, artifact: CompilerOutputContract): void {
  // Save contract ABI to file
  if (artifact.abi.length > 0) {
    const abiDirectory = path.resolve(task.dir(), 'abi');
    if (!existsSync(abiDirectory)) {
      mkdirSync(abiDirectory);
    }
    const abiFilePath = path.resolve(abiDirectory, `${contractName}.json`);
    writeFileSync(abiFilePath, JSON.stringify(artifact.abi, null, 2));
  }

  // Save contract bytecode to file
  const bytecodeDirectory = path.resolve(task.dir(), 'bytecode');
  if (!existsSync(bytecodeDirectory)) {
    mkdirSync(bytecodeDirectory);
  }
  const bytecodeFilePath = path.resolve(bytecodeDirectory, `${contractName}.json`);
  writeFileSync(bytecodeFilePath, JSON.stringify({ creationCode: artifact.evm.bytecode.object }, null, 2));
}
Example #3
Source File: Options.ts    From tf2autobot with MIT License 6 votes vote down vote up
test('malformed json in the files dir should crash', () => {
    const filesPath = Options.getFilesPath('abc123');
    cleanPath(filesPath);
    const malformedJsonFile = '{"good": "entry",\r\n"unclosed": "string}';
    const malformedFilePath = path.join(filesPath, 'bad.json');
    mkdirSync(filesPath, { recursive: true });
    writeFileSync(malformedFilePath, malformedJsonFile, { encoding: 'utf8' });
    expect(() => {
        Options.loadOptions({ steamAccountName: 'abc123' });
    }).toThrow(
        new Error(
            `${malformedFilePath}\n` +
                "Parse error on line 2:\n...ntry\",\r\"unclosed\": \"string}\n----------------------^\nExpecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'"
        )
    );
});
Example #4
Source File: prerender.ts    From ng-event-plugins with Apache License 2.0 6 votes vote down vote up
// Iterate each route path
PRERENDERED_ROUTES.forEach(route => {
    const fullPath = join(DEMO_FOLDER, route);

    // Make sure the directory structure is there
    if (!existsSync(fullPath)) {
        mkdirSync(fullPath);
    }

    // Writes rendered HTML to index.html, replacing the file if it already exists.
    previousRender = previousRender
        .then(() =>
            renderModuleFactory(AppServerModuleNgFactory, {
                document: index,
                url: route,
                extraProviders: [
                    provideModuleMap(LAZY_MODULE_MAP),
                    {
                        provide: APP_BASE_HREF,
                        useValue: process.env.ORIGIN || localFallback,
                    },
                ],
            }),
        )
        .then(html => writeFileSync(join(fullPath, 'index.html'), html));
});
Example #5
Source File: context.ts    From lage with MIT License 6 votes vote down vote up
export function createContext(
  config: Pick<Config, "concurrency" | "profile" | "dist" | "workerQueueOptions">
): RunContext {
  const { concurrency, profile } = config;

  const useCustomProfilePath = typeof profile === "string";

  const profilerOutputDir = useCustomProfilePath ? dirname(profile as string) : join(tmpdir(), "lage", "profiles");

  mkdirSync(profilerOutputDir, { recursive: true });

  const profiler = new Profiler(
    useCustomProfilePath
      ? {
          concurrency,
          customOutputPath: profile as string,
        }
      : {
          concurrency,
          prefix: "lage",
          outDir: profilerOutputDir,
        }
  );

  return {
    measures: {
      start: [0, 0],
      duration: [0, 0],
      failedTargets: [],
    },
    targets: new Map(),
    profiler,
    workerQueue: config.dist ? new WorkerQueue(config) : undefined,
  };
}
Example #6
Source File: index.ts    From swagger-typescript with MIT License 6 votes vote down vote up
function generateMock(content: any, config: Config) {
  const { dir } = config;
  try {
    const output = `${dir}/mocks`;
    const responses = extractResponses(content, config);
    const schemas = extractSchemas(content);
    const composed = composeMockData(responses, schemas);

    if (!existsSync(output)) {
      mkdirSync(output);
    }
    writeFiles(composed, output);

    console.log(chalk.yellowBright("Mocks Completed"));
  } catch (e) {
    console.log(chalk.redBright(e));
    console.log(chalk.redBright("Mocks Failed"));
  }
}
Example #7
Source File: init.ts    From OpenVolunteerPlatform with MIT License 6 votes vote down vote up
/**
 * init command handler
 * @param name name of project folder
 * @param templateName name of the template provided(if any)
 * @param templateUrl github url to the template
 */
export async function init(name: string, templateName?: string, templateUrl?: string) {
  logInfo(chalk.yellow(
    figlet.textSync('Open Volunteer', { horizontalLayout: 'full' })
  ))
  const path: string = `${process.cwd()}/${name}`
  checkDirectory(path, name)
  let template: Template;
  if (templateUrl) {
    template = buildTemplateFromGithub(templateUrl);
  } else {
    template = await assignTemplate(templateName)
  }
  mkdirSync(path)
  logInfo(`
Bootstraping graphql server :dizzy: :sparkles:`)
  await extractTemplate(template, name)
  process.chdir(name)
  logInfo(postSetupMessage(name))
}
Example #8
Source File: prerender.ts    From fab-menu with MIT License 6 votes vote down vote up
// Iterate each route path
ROUTES.forEach(route => {
  const fullPath = join(BROWSER_FOLDER, route);

  // Make sure the directory structure is there
  if (!existsSync(fullPath)) {
    mkdirSync(fullPath);
  }

  // Writes rendered HTML to index.html, replacing the file if it already exists.
  previousRender = previousRender
    .then(_ =>
      renderModuleFactory(AppServerModuleNgFactory, {
        document: index,
        url: route,
        extraProviders: [provideModuleMap(LAZY_MODULE_MAP)]
      })
    )
    .then(html => writeFileSync(join(fullPath, 'index.html'), html));
});
Example #9
Source File: evm.ts    From airnode with MIT License 6 votes vote down vote up
deployContract = async (artifactsFolderPath: string, args: any[] = []) => {
  const artifact = getArtifact(artifactsFolderPath);

  // Deploy the contract
  const contractFactory = new ethers.ContractFactory(artifact.abi, artifact.bytecode, await getUserWallet());
  const contract = await contractFactory.deploy(...args);
  await contract.deployed();

  // Make sure the deployments folder exist
  const deploymentsPath = join(__dirname, '../deployments');
  if (!existsSync(deploymentsPath)) mkdirSync(deploymentsPath);

  // Try to load the existing deployments file for this network - we want to preserve deployments of other contracts
  const network = readIntegrationInfo().network;
  const deploymentPath = join(deploymentsPath, network + '.json');
  let deployment: any = {};
  if (existsSync(deploymentPath)) deployment = JSON.parse(readFileSync(deploymentPath).toString());

  // The key name for this contract is the path of the artifact without the '.sol' extension
  const deploymentName = removeExtension(artifactsFolderPath);
  // Write down the address of deployed contract
  writeFileSync(deploymentPath, JSON.stringify({ ...deployment, [deploymentName]: contract.address }, null, 2));

  return contract;
}
Example #10
Source File: index.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export function generateSourceCode(projectRoot: string, srcDir: string) : string {
  const userFileData = 'This is a pre-existing file.';
  const srcCodePath = path.join(projectRoot, srcDir, 'sample.txt');
  if (!existsSync(path.dirname(srcCodePath))) {
    mkdirSync(path.dirname(srcCodePath), {recursive: true});
  }
  writeFileSync(srcCodePath, userFileData);
  return srcCodePath;
}
Example #11
Source File: Options.ts    From tf2autobot with MIT License 6 votes vote down vote up
test('loads a subset of options', () => {
    const filesPath = Options.getFilesPath('abc123');
    cleanPath(filesPath);
    const rawOptions = '{"miscSettings":{"addFriends":{"enable":false},"sendGroupInvite":{"enable":false}}}';
    const optionsFilePath = path.join(filesPath, 'options.json');
    mkdirSync(filesPath, { recursive: true });
    writeFileSync(optionsFilePath, rawOptions, { encoding: 'utf8' });
    const result = Options.loadOptions({
        steamAccountName: 'abc123',
        miscSettings: { addFriends: { enable: false }, sendGroupInvite: { enable: false } }
    });
    expect(result.miscSettings.addFriends.enable).toBeFalsy();
    expect(result.miscSettings.sendGroupInvite.enable).toBeFalsy();
});
Example #12
Source File: SaveData.ts    From YoutubeLiveApp with MIT License 6 votes vote down vote up
export function resumeData(): SaveData {
  try {
    const recentState = JSON.parse(readFileSync(appStateFilePath).toString("utf-8")) as SaveData;
    return recentState;
  } catch (e) {
    try {
      mkdirSync(".save");
    } catch (e) {
      /* NOP */
    }
    return { ...createInitialState("https://studio.youtube.com/"), isAlwaysOnTop: false, fixedChatUrl: false };
  }
}
Example #13
Source File: expandedPreviewer.ts    From cli with Apache License 2.0 6 votes vote down vote up
public async preview() {
    if (existsSync(ExpandedPreviewer.previewDirectory)) {
      this.deleteOldestPreviews();
    }
    const previewLocalSlug = `${this.orgId}-${Date.now()}`;
    const dirPath = join(ExpandedPreviewer.previewDirectory, previewLocalSlug);

    mkdirSync(dirPath, {
      recursive: true,
    });
    const project = new Project(resolve(dirPath));
    CliUx.ux.action.start('Generating preview details');
    await this.initPreviewDirectory(dirPath, project);
    await this.applySnapshotToPreview(dirPath);
    const commitHash = await this.getCommitHash(dirPath);

    CliUx.ux.info(dedent`

    A Git repository representing the modification has been created here:
    ${dirPath}

    with the associated commit hash: ${commitHash.stdout}
    `);
    CliUx.ux.action.stop(green('✔'));
  }
Example #14
Source File: util.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
export function unpackZip(file: Buffer, id: string): string {
  const zip = new AdmZip(file);
  const path = join(config().wasmBuild.rootFolder, id);
  mkdirSync(path, { recursive: true });
  zip.extractAllTo(path);
  return path;
}
Example #15
Source File: command-config.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** Load configuration from config path or creates config folder */
  private prepareConfig() {
    if (!existsSync(this.configFilePath)) {
      if (!existsSync(this.configFolderPath)) mkdirSync(this.configFolderPath, { mode: 0o700, recursive: true })

      //save config initialized in constructor
      this.saveConfig()
    } else {
      //load config
      const configData = readFileSync(this.configFilePath)
      try {
        this.config = JSON.parse(configData.toString())
      } catch (err) {
        this.console.error(
          `There has been an error parsing JSON configuration of CLI from path: '${this.configFilePath}'`,
        )

        exit(1)
      }
    }
  }
Example #16
Source File: Options.ts    From tf2autobot with MIT License 6 votes vote down vote up
test('write options.json if no file exists in directory', () => {
    const optionsPath = Options.getOptionsPath('abc123');
    cleanPath(path.dirname(optionsPath));
    Options.loadOptions({ steamAccountName: 'abc123' }); // options should create directory and write defaults
    expect(readFileSync(optionsPath, { encoding: 'utf8' })).toEqual(JSON.stringify(Options.DEFAULTS, null, 4));
    cleanPath(path.dirname(optionsPath));
    mkdirSync(path.dirname(optionsPath)); // now only the directory exists but no options.json
    Options.loadOptions({ steamAccountName: 'abc123' });
    expect(readFileSync(optionsPath, { encoding: 'utf8' })).toEqual(JSON.stringify(Options.DEFAULTS, null, 4));
});
Example #17
Source File: bundle.ts    From luabundler with MIT License 6 votes vote down vote up
async run() {
		const {args, flags} = this.parse(BundleCommand)
		const options: BundleOptions = {
			luaVersion: flags.lua,
			isolate: flags.isolate,
			expressionHandler: (module: Module, expression: Expression) => {
				const start = expression.loc!.start
				console.warn(`WARNING: Non-literal require found in '${module.name}' at ${start.line}:${start.column}`)
			},
		}

		if (flags.path.length > 0) {
			options.paths = flags.path
		}

		let content

		if (!args.file || args.file === '-') {
			content = bundleString(await readStdin(), options)
		} else {
			content = bundle(args.file, options)
		}

		if (flags.output) {
			const resolvedPath = resolvePath(flags.output)
			const resolvedDir = dirname(resolvedPath)

			if (!existsSync(resolvedDir)) {
				mkdirSync(resolvedDir, {recursive: true})
			}

			writeFileSync(flags.output, content)
		} else {
			console.log(content)
		}
	}
Example #18
Source File: compare-pdf-to-snapshot.ts    From pdf-visual-diff with MIT License 6 votes vote down vote up
comparePdfToSnapshot = (
  pdf: string | Buffer,
  snapshotDir: string,
  snapshotName: string,
  { maskRegions, ...restOpts }: Partial<CompareOptions> = {},
): Promise<boolean> => {
  const dir = join(snapshotDir, snapshotsDirName)
  if (!existsSync(dir)) {
    mkdirSync(dir, { recursive: true })
  }

  const snapshotPath = join(dir, snapshotName + '.png')

  if (!existsSync(snapshotPath)) {
    return pdf2png(pdf)
      .then(maskImgWithRegions(maskRegions || []))
      .then(writeImages(snapshotPath))
      .then(() => true)
  }

  return pdf2png(pdf)
    .then(maskImgWithRegions(maskRegions || []))
    .then((images) =>
      compareImages(snapshotPath, images, restOpts).then((result) => {
        const diffSnapshotPath = join(dir, snapshotName + '.diff.png')
        if (result.equal) {
          if (existsSync(diffSnapshotPath)) {
            unlinkSync(diffSnapshotPath)
          }
          return true
        }

        const newSnapshotPath = join(dir, snapshotName + '.new.png')
        return writeImages(newSnapshotPath)(images)
          .then(() => writeImages(diffSnapshotPath)(result.diffs.map((x) => x.diff)))
          .then(() => false)
      }),
    )
}
Example #19
Source File: index.ts    From storybook with MIT License 6 votes vote down vote up
export function eject (options: StorybookOptions) {
  const configDir = path.resolve(options.rootDir, '.storybook')
  const templatesRoot = path.resolve(__dirname, '../storybook')
  if (existsSync(configDir)) {
    if (!options.force) {
      logger.warn('Storybook is already ejected, use `--force` to overwrite files.')
      return
    }
  } else {
    mkdirSync(configDir)
  }
  compileTemplate(path.resolve(templatesRoot, 'eject', 'main.js'), path.join(configDir, 'main.js'), {})
  compileTemplate(path.resolve(templatesRoot, 'eject', 'middleware.js'), path.join(configDir, 'middleware.js'), {})
  compileTemplate(path.resolve(templatesRoot, 'eject', 'preview.js'), path.join(configDir, 'preview.js'), {})
}
Example #20
Source File: System.ts    From Dimensions with MIT License 6 votes vote down vote up
writeFileToDestination = async (
  file: string,
  destination: string
): Promise<void> => {
  return new Promise((resolve) => {
    if (!fs.existsSync(path.dirname(destination))) {
      mkdirSync(path.dirname(destination), {
        recursive: true,
      });
    }
    fs.createReadStream(file)
      .pipe(fs.createWriteStream(destination))
      .on('close', () => {
        resolve();
      });
  });
}
Example #21
Source File: terminal.ts    From vscode-cadence with Apache License 2.0 6 votes vote down vote up
// Returns a path to a directory that can be used for persistent storage.
// Creates the directory if it doesn't already exist.
function getStoragePath (ctx: ExtensionContext): string | undefined {
  let storagePath = ctx.storagePath // ref: deprecated
  if (storagePath === undefined) {
    storagePath = ctx.globalStoragePath
  }
  console.log('Storage path: ', storagePath)
  if (!existsSync(storagePath)) {
    try {
      mkdirSync(storagePath)
    } catch (err) {
      console.log('Error creating storage path: ', err)
      return
    }
  }
  return storagePath
}
Example #22
Source File: index.ts    From Dimensions with MIT License 6 votes vote down vote up
/**
   * Retrieves a bot through its key and downloads it to a random generated folder. Returns the new file's path
   * @param botkey
   * @param file
   * @param useCached - if true, storage plugin will avoid redownloading data. If false, storage plugin will always
   * redownload data
   */
  private async retrieveBot(botkey: string, file: string, useCached: boolean) {
    const dir = BOT_DIR + '/anon-' + genID(18);
    mkdirSync(dir);

    const zipFile = path.join(dir, 'bot.zip');
    // if useCached is true, actualZipFileLocation will likely be different than zipFile, and we directly re-extract
    // the bot from that zip file. It can be argued that it would be better to cache the unzipped bot instead but this
    // could potentially be a security concern by repeatedly copying over unzipped bot files instead of the submitted
    // zip file; and zip is smaller to cache
    const actualZipFileLocation = await this.dimension.storagePlugin.download(
      botkey,
      zipFile,
      useCached
    );

    await extract(actualZipFileLocation, {
      dir: dir,
    });
    return path.join(dir, path.basename(file));
  }
Example #23
Source File: rss.ts    From oxen-website with GNU General Public License v3.0 6 votes vote down vote up
export default function generateRSSFeed(posts: IPost[]) {
  posts.forEach(post => {
    const postLink = `${baseUrl}/blog/${post.slug}`;
    const postContent = `<p>${post.description}</p><p><a href="${postLink}">Read more</a></p>`;
    feed.addItem({
      title: post.title,
      id: postLink,
      link: postLink,
      description: post.description,
      content: postContent,
      date: new Date(post.publishedDate),
    });
  });

  mkdirSync(`./public/rss`, { recursive: true });
  writeFileSync(`./public/rss/feed.xml`, feed.rss2(), {
    encoding: 'utf-8',
    flag: 'w',
  });
  writeFileSync(`./public/rss/feed.json`, feed.json1(), {
    encoding: 'utf-8',
    flag: 'w',
  });
  writeFileSync(`./public/rss/atom.xml`, feed.atom1(), {
    encoding: 'utf-8',
    flag: 'w',
  });
}
Example #24
Source File: ConfigManager.ts    From discord-qt with GNU General Public License v3.0 6 votes vote down vote up
constructor(private file: string) {
    try {
      mkdirSync(dirname(file), { recursive: true });
    } catch (e) {
      warn('Could not load config.');
    }

    setInterval(() => {
      void this.save();
    }, 1000);
  }
Example #25
Source File: images.ts    From blog with GNU General Public License v3.0 6 votes vote down vote up
copyLocalImage = async (imagePath: string, postId: string, postPath: string): Promise<string> => {
    const imageName = basename(imagePath).replace(/\s/g,'-');
    const newPath = join('assets', postId);

    console.log(`Copying image ${join(postPath, imagePath)}`);

    mkdirSync(join(publicPath, newPath), {
        recursive: true
    });
    copyFileSync(join(postPath, imagePath), join(publicPath, newPath, imageName));

    console.log(`Copied to ${join(newPath, imageName)}`);

    return join(newPath, imageName);
}
Example #26
Source File: copy-eslint-config.ts    From s-libs with MIT License 6 votes vote down vote up
export function copyEslintConfig() {
  const targetFolder = 'dist/eslint-config-ng';
  rmdirSync(targetFolder, { recursive: true });
  mkdirSync(targetFolder);

  const srcFolder = 'projects/eslint-config-ng';
  for (const file of readdirSync(srcFolder)) {
    copyFileSync(join(srcFolder, file), join(targetFolder, file));
  }
}
Example #27
Source File: createProject.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
export async function run(args: any) {
  // get workspace folder
  let workspaceFolders = Workspace.workspaceFolders;
  if (!workspaceFolders) {
    window.showErrorMessage("No workspace are opened.");
    return;
  }

  const inputOptions: InputBoxOptions = {
    prompt:
      "Relative path for the root of the project. Leave empty for the root ",
  };

  const input = await window.showInputBox(inputOptions);

  //Select the rootpath
  let rootpath = join(workspaceFolders?.[0].uri.fsPath, input);
  if (!existsSync(rootpath)) {
    mkdirSync(rootpath);
  }

  // Create the plugins folder
  let pluginsFolderPath = join(rootpath, "plugins");
  if (!existsSync(pluginsFolderPath)) {
    mkdirSync(pluginsFolderPath);
  }

  // Running the other commands
  createTaskCommand(rootpath);
  createScriptCommand(rootpath);
  createREADMECommand(rootpath);
  createMasterCommand(rootpath);
  createChangelogCommand(rootpath);
}
Example #28
Source File: images.ts    From blog with GNU General Public License v3.0 6 votes vote down vote up
copyRemoteImage = async (imageUrl: string, postId: string, postPath: string): Promise<string> => {
    const newPath = join('assets', postId);
    mkdirSync(join(publicPath, newPath), {
        recursive: true
    });
    const url = new URL(imageUrl);
    const imageName = basename(url.pathname);
    console.log('Copying remote image ' + imageUrl);
    // GET request for remote image in node.js
    const response = await axios({
        method: 'get',
        url: imageUrl,
        responseType: 'stream'
    });
    response.data.pipe(createWriteStream(join(publicPath, newPath, imageName)));
    console.log(`Copied to ${join(newPath, imageName)}`);
    return join(newPath, imageName);
}
Example #29
Source File: buildUMD.ts    From fzstd with MIT License 5 votes vote down vote up
minify(src, opts).then(out => {
  const res = "!function(f){typeof module!='undefined'&&typeof exports=='object'?module.exports=f():typeof define!='undefined'&&define.amd?define(['fzstd',f]):(typeof self!='undefined'?self:this).fzstd=f()}(function(){var _e={};" +
    out.code!.replace(/exports\.(.*) = void 0;\n/, '').replace(/exports\./g, '_e.') + 'return _e})';
  if (!existsSync(p('umd'))) mkdirSync(p('umd'));
  writeFileSync(p('umd', 'index.js'), res);
});