fs#writeFileSync TypeScript Examples

The following examples show how to use fs#writeFileSync. 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
function writeDefaultConfigData() {

    const defaultConfigData = {
        apiUrl: defaultApiUrl,
        credentials: 'empty'
    };

    writeFileSync(
        configFilePath,
        JSON.stringify(defaultConfigData),
        {
            flag: 'w',
            encoding: 'utf8',
        }
    );
}
Example #2
Source File: generate-configs.ts    From graphql-eslint with MIT License 6 votes vote down vote up
writeFormattedFile: WriteFile = (filePath, code): void => {
  const isJson = filePath.endsWith('.json');

  const formattedCode = isJson
    ? format(JSON.stringify(code), {
        parser: 'json',
        printWidth: 80,
      })
    : [
        '/*',
        ' * ? IMPORTANT! Do not manually modify this file. Run: `yarn generate-configs`',
        ' */',
        BR,
        format(code, {
          ...prettierOptions,
          parser: 'typescript',
        }),
      ].join('\n');

  writeFileSync(join(SRC_PATH, filePath), formattedCode);
  // eslint-disable-next-line no-console
  console.log(`✅  ${chalk.green(filePath)} file generated`);
}
Example #3
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 #4
Source File: nx-npm.spec.ts    From nx-plugins with MIT License 6 votes vote down vote up
describe('nx-npm e2e', () => {
  beforeAll(async () => {
    ensureComplexNxProject(
      ['@ns3/nx-npm', 'dist/packages/nx-npm'],
      ['@ns3/nx-core', 'dist/packages/nx-core'],
    );
    const pmc = getPackageManagerCommand();
    await runCommandAsync(`${pmc.addDev} @nrwl/node`);
    const p = JSON.parse(readFileSync(tmpProjPath('package.json')).toString());
    p['repository'] = {
      type: 'git',
      url: 'https://github.com/Bielik20/nx-plugins',
    };
    writeFileSync(tmpProjPath('package.json'), JSON.stringify(p, null, 2));
  });

  it('should create nx-npm', async () => {
    const plugin = uniq('nx-npm');

    await runNxCommandAsync(
      `generate @nrwl/node:lib ${plugin} --publishable --importPath ${plugin}`,
    );
    await runNxCommandAsync(`generate @ns3/nx-npm:npm --project ${plugin}`);

    const buildResult = await runNxCommandAsync(`build ${plugin}`);
    const publishResult = await runNxCommandAsync(`publish ${plugin} --npmToken noop --dryRun`);

    expect(publishResult.stderr).toContain('Tarball Contents');
    expect(publishResult.stderr).toContain('Tarball Details');
  });
});
Example #5
Source File: updateJSONFixtures.ts    From dt-mergebot with MIT License 6 votes vote down vote up
fixtureNames.forEach(fixture => {
    const responsePath = join(fixtureRoot, fixture, "_response.json");
    const response = JSON.parse(readFileSync(responsePath, "utf8"));
    const pr = response.data.repository.pullRequest;
    const headSha =  pr.headRefOid;

    if (!pr.commits) return;

    const headCommit = pr.commits.nodes.find((c: any) => c.commit.oid === headSha).commit;
    const status = headCommit.status && headCommit.status.state || "MISSING";

    if (!headCommit.checkSuites) headCommit.checkSuites = { nodes: [] };
    headCommit.checkSuites.nodes.push({
        "app": {
            "name": "GitHub Actions",
            "__typename": "App",
        },
        "conclusion": status,
        "resourcePath": "/DefinitelyTyped/DefinitelyTyped/commit/22c73c88cc9c09efd4c2998ec360607dd4c36c2e/checks?check_suite_id=731664306",
        "status": status,
        "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/commit/22c73c88cc9c09efd4c2998ec360607dd4c36c2e/checks?check_suite_id=731664306",
        "__typename": "CheckSuite",
    });

    writeFileSync(responsePath, JSON.stringify(response, null, "  ") + "\n", "utf8");
});
Example #6
Source File: LKBootstrap.ts    From iOSreExtension with Apache License 2.0 6 votes vote down vote up
public ensureLocalBins(location: String) {
        console.log("[*] Looking for items under " + location);

        execSync("rm -f \'" + location + "/lkbins.zip\' &> /dev/null");
        execSync("rm -rf \'" + location + "/lkbins\' &> /dev/null");
        execSync("mkdir -p \'" + location + "/\' &> /dev/null");
        // clean scripts
        // execSync("find \'" + location + "/\' -name \'??????*\' -delete &> /dev/null");

        writeFileSync(location + "/lkbins.zip", LKBootStrap.binpackcode, "base64");
        this.binloc = location + "/lkbins";
        var zip = new AdmZip(location + "/lkbins.zip");
        // @ts-ignore
        zip.extractAllTo(location + "/lkbins");
        execSync("chmod -R 777 \'" + location + "/lkbins\'");
    }
Example #7
Source File: extension.ts    From dockerfiletemplate with MIT License 6 votes vote down vote up
export function createDockerFile(
  templatePath: String,
  workspaceFolder: String
): Boolean {
  try {
    const data = readFileSync(normalize(`${__dirname}/${templatePath}`));
    writeFileSync(`${workspaceFolder}/Dockerfile`, data);
  } catch (error: any) {
    throw new Error(error);
  }
  return true;
}
Example #8
Source File: Options.ts    From tf2autobot with MIT License 6 votes vote down vote up
test('malformed options.json should crash', () => {
    const optionsPath = Options.getOptionsPath('abc123');
    cleanPath(path.dirname(optionsPath));
    Options.loadOptions({ steamAccountName: 'abc123' }); // make default options get loaded
    const malformedOptions = '{"good": "entry",\r\n"unclosed": "string}';
    writeFileSync(optionsPath, malformedOptions, { encoding: 'utf8' }); // options are now mangled
    expect(() => {
        Options.loadOptions({ steamAccountName: 'abc123' });
    }).toThrow(
        new Error(
            `${optionsPath}\n` +
                "Parse error on line 2:\n...ntry\",\r\"unclosed\": \"string}\n----------------------^\nExpecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'"
        )
    );
    // ensure options.json is left untouched
    const rawOptions = readFileSync(optionsPath, { encoding: 'utf8' });
    expect(rawOptions).toEqual('{"good": "entry",\r\n"unclosed": "string}');
});
Example #9
Source File: compareImages.ts    From cucumber-playwright with MIT License 6 votes vote down vote up
export async function compareToBaseImage(
  customWorld: ICustomWorld,
  name: string,
  screenshot: Buffer,
  threshold?: { threshold: number },
) {
  let baseImage;
  const baseImagePath = getImagePath(customWorld, name);
  const baseImgExist = await pathExists(baseImagePath);
  if (baseImgExist) {
    baseImage = PNG.sync.read(fs.readFileSync(baseImagePath));
  } else {
    await ensureFile(baseImagePath);
    writeFileSync(baseImagePath, screenshot);
    customWorld.log(
      `The base Image doesn't exist, a screenshot was taken to ${baseImagePath} so it can be used for next run`,
    );
    return;
  }
  const img1 = PNG.sync.read(screenshot);
  const difference = getDifference(img1, baseImage, threshold);
  if (difference) {
    await customWorld.attach(difference, 'image/png;base64');
    throw new Error(`Screenshot does not match : ${baseImagePath}`);
  }
}
Example #10
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 #11
Source File: read-file-or-url.spec.ts    From graphql-mesh with MIT License 6 votes vote down vote up
describe('readFile', () => {
  it('should convert relative paths to absolute paths correctly', async () => {
    const tmpFileAbsolutePath = join(tmpdir(), './tmpfile.json');
    const tmpFileContent = {
      test: 'TEST',
    };
    writeFileSync(tmpFileAbsolutePath, JSON.stringify(tmpFileContent));
    const tmpFileRelativePath = relative(cwd(), tmpFileAbsolutePath);
    const receivedFileContent = await readFile(tmpFileRelativePath);
    expect(receivedFileContent).toStrictEqual(tmpFileContent);
  });
  it('should respect absolute paths correctly', async () => {
    const tmpFileAbsolutePath = join(tmpdir(), './tmpfile.json');
    const tmpFileContent = {
      test: 'TEST',
    };
    writeFileSync(tmpFileAbsolutePath, JSON.stringify(tmpFileContent));
    const receivedFileContent = await readFile(tmpFileAbsolutePath);
    expect(receivedFileContent).toStrictEqual(tmpFileContent);
  });
});
Example #12
Source File: runBatch.ts    From elephize with MIT License 6 votes vote down vote up
function onData(basePath: string[], promises: Array<Promise<any>>, filename: string, content: string) {
  process.stdout.write('[data received] ' + filename + '\n');
  promises.push(new Promise((resolve) => {
    const resultFileName = join(baseDir, normalizeFileExt(filename));
    const cont = prettier.format(content, phpPrettierOptions);

    mkdirpSync(dirname(resultFileName));

    writeFileSync(resultFileName + '.result', cont, 'utf-8');
    expect(cont).toBeTruthy();
    expect(cont, 'Failed in file: ' + filename)
      .toEqual(prettier.format(readFileSync(resultFileName, 'utf-8'), phpPrettierOptions));
    process.stdout.write('[test ok] ' + filename.replace(pResolve(...basePath), '') + '\n');
    unlinkSync(resultFileName + '.result');
    resolve(null);
  }));
}
Example #13
Source File: generate-ffmpeg-file.ts    From beacon-sdk with MIT License 6 votes vote down vote up
generateFFMPEGFile = (path: string) => {
  const files = readdirSync(path)

  const output = files
    .filter((file) => file.endsWith('.jpg'))
    .map((file, i, arr) => {
      let duration = 100
      if (i + 1 < arr.length) {
        const currentTimestamp = Number(file.slice(7, 13))
        const futureTimestamp = Number(arr[i + 1].slice(7, 13))
        duration = futureTimestamp - currentTimestamp
      }
      console.log(file, duration)
      return `file '${file}'\nduration ${duration / 1000}`
    })
    .join('\n')

  writeFileSync(`${path}/input.txt`, output)
}
Example #14
Source File: commentOperations.ts    From typescript-strict-plugin with MIT License 6 votes vote down vote up
export function removeStrictComment(filePath: string) {
  const fileContent = readFileSync(filePath, 'utf-8');

  const data = fileContent
    .split('\n')
    .filter((line) => !line.includes(TS_STRICT_COMMENT))
    .join('\n');

  if (data !== fileContent) {
    writeFileSync(filePath, data);
  }
}
Example #15
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 #16
Source File: index.ts    From html2sketch with MIT License 6 votes vote down vote up
outputJSONData = (
  json:
    | SketchFormat.Group
    | SketchFormat.ShapeGroup
    | SketchFormat.SymbolMaster,
  name: string,
) => {
  writeFileSync(join(__dirname, `./json/${name}.json`), JSON.stringify(json));
}
Example #17
Source File: createWskdeployProject.test.ts    From openwhisk-vscode-extension with Apache License 2.0 6 votes vote down vote up
suite('templateGenerator.createWskdeployProject', async function () {
    test('Create wskdeploy project files', async () => {
        const fakeConfirm = sinon.fake.returns(Promise.resolve({ action: 'confirm' }));
        sinon.replace(vscode.window, 'showInformationMessage', fakeConfirm);
        await createWskdeployProject();
        await timeout(1000);
        expect(existsSync(MANIFESTFILE_PATH)).to.be.true;
    });

    test('Show warning message if manifest file exists', async () => {
        writeFileSync(MANIFESTFILE_PATH, '');
        sinon.spy(vscode.window, 'showErrorMessage');
        await createWskdeployProject();
        // @ts-ignore
        const spyCall = vscode.window.showErrorMessage.getCall(0);
        expect(spyCall.args[0].includes('already exists')).to.be.true;
    });

    afterEach(() => {
        rimraf.sync(SRC_DIR_PATH);
        rimraf.sync(MANIFESTFILE_PATH);
    });
});
Example #18
Source File: config-utils.ts    From airnode with MIT License 6 votes vote down vote up
generateConfigFile = (dirname: string, config: Config, generateExampleFile: boolean) => {
  const filename = generateExampleFile ? 'config.example.json' : 'config.json';
  writeFileSync(join(dirname, filename), JSON.stringify(config, null, 2) + '\n');

  cliPrint.info(`A '${filename}' has been created.`);
}
Example #19
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 #20
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 #21
Source File: server.ts    From omegga with ISC License 6 votes vote down vote up
loadEnvironmentData(
    preset: EnvironmentPreset | EnvironmentPreset['data']['groups']
  ) {
    if ('data' in preset) preset = preset.data.groups;

    const saveFile =
      this._tempSavePrefix + Date.now() + '_' + this._tempCounter.environment++;

    const path = join(this.presetPath, 'Environment', saveFile + '.bp');

    writeFileSync(
      path,
      JSON.stringify({
        formatVersion: '1',
        presetVersion: '1',
        type: 'Environment',
        data: {
          groups: {
            ...preset,
          },
        },
      })
    );

    this.loadEnvironment(saveFile);

    // this is lazy, but environments should load much faster than builds
    // do, so it's not really worth keeping track of logs for this
    setTimeout(() => unlinkSync(path), 5000);
  }
Example #22
Source File: peHibpSync.ts    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
handler = async (commandOptions: CommandOptions) => {
  const { organizationId, organizationName } = commandOptions;
  await connectToDatabase();
  const vulnerabilities = await Vulnerability.createQueryBuilder('vuln')
    .select('vuln.structuredData', 'structuredData')
    .addSelect('dom.fromRootDomain', 'fromRootDomain')
    .addSelect('dom.name', 'name')
    .innerJoin('vuln.domain', 'dom')
    .where('dom.organizationId = :org_id', { org_id: organizationId })
    .andWhere("vuln.source = 'hibp'")
    .getRawMany();

  const INPUT_PATH = path.join(HIBP_SYNC_DIRECTORY, organizationId + '.json');
  writeFileSync(INPUT_PATH, JSON.stringify(vulnerabilities));
  const child = spawnSync(
    'python3',
    ['/app/worker/pe_scripts/sync_hibp_pe.py'],
    {
      stdio: 'pipe',
      encoding: 'utf-8',
      env: {
        ...getPeEnv(),
        data_path: INPUT_PATH,
        org_name: organizationName,
        org_id: organizationId
      }
    }
  );
  const savedOutput = child.stdout;
  console.log(savedOutput);
}
Example #23
Source File: settings.ts    From project-loved-web with MIT License 6 votes vote down vote up
export function updateSettings(newSettings: Record<string, unknown>): string[] {
  const modifiedSettings: string[] = [];

  for (const [key, value] of Object.entries(newSettings)) {
    if (updateSetting(key, value)) {
      modifiedSettings.push(key);
    }
  }

  writeFileSync(settingsPath, JSON.stringify(settings));

  return modifiedSettings;
}
Example #24
Source File: add-js-extensions.ts    From blake3 with MIT License 6 votes vote down vote up
/**
 * Script that adds .js extension to imports so that it's compatible with plain
 * browser/non-webpack bundlers. TS doesn't support this natively yet.
 * @see https://github.com/microsoft/TypeScript/issues/16577
 */

function processFile(file: string) {
  let source = readFileSync(file, 'utf-8');
  const program = ts.createSourceFile(basename(file), source, ts.ScriptTarget.ES2015, true);

  let offset = 0;
  const process = (node: ts.Node): void => {
    if ((!ts.isImportDeclaration(node) && !ts.isExportDeclaration(node)) || !node.moduleSpecifier) {
      return ts.forEachChild(node, process);
    }

    const specifier = node.moduleSpecifier;
    if (extname(specifier.getText()) === '') {
      const idx = specifier.end + offset - 1;
      source = source.slice(0, idx) + '.js' + source.slice(idx);
      offset += 3;
    }
  };

  process(program);

  writeFileSync(file, source);
}
Example #25
Source File: test-helpers.ts    From graphql-typed-document-node with MIT License 6 votes vote down vote up
export function prepareTempProject(extraDeps = {}): { dir: string, patch: () => void } {
  const projectDirectory = dirSync();

  writeFileSync(join(projectDirectory.name, './package.json'), JSON.stringify({
    name: "test",
    license: 'MIT',
    dependencies: {
      '@types/react': 'latest',
      '@types/node': allDeps['@types/node'],
      'graphql': allDeps.graphql,
      '@graphql-typed-document-node/core': join(process.cwd(), './packages/core/dist/'),
      '@graphql-typed-document-node/patch-cli': join(process.cwd(), './packages/patch-cli/dist/'),
      ...extraDeps,
    },
    scripts: {
      patch: "patch-typed-document-node" 
    }
  }, null, 2));

  execSync('yarn install', {
    stdio: ['ignore', 'ignore', 'ignore'],
    cwd: projectDirectory.name,
  });

  return {
    dir: projectDirectory.name,
    patch: () => {
      const out = execSync('yarn patch', {
        cwd: projectDirectory.name,
      });
      // eslint-disable-next-line
      console.log(out.toString());
    }
  };
}
Example #26
Source File: TimelapseNotification.ts    From mooncord with MIT License 6 votes vote down vote up
protected async compressTimelapse(timelapseBuffer: Buffer, timelapseName: string) {
        const absolutePath = (this.configHelper.getTempPath().startsWith('..')) ? path.join(__dirname, this.configHelper.getTempPath()) : this.configHelper.getTempPath()
        const tempPath = path.join(absolutePath, timelapseName)
        const tempPathShort = path.join(absolutePath, `compressed-${timelapseName}`)
        let renderComplete = false

        logRegular(`Compress Timelapse: ${timelapseName}`)

        writeFileSync(tempPath, timelapseBuffer,{encoding: 'utf8', flag: 'w+'})

        this.ffmpegRender
            .addInput(tempPath)
            .noAudio()
            .output(tempPathShort)
            .outputOptions(this.ffmpegArguments)
            .on('end', async (stdout, stderr) => {
                renderComplete = true
            })

        this.ffmpegRender.run()

        await waitUntil(() => renderComplete === true, { timeout: Number.POSITIVE_INFINITY })

        logSuccess(`Compressed Timelapse: ${timelapseName}`)

        unlinkSync(tempPath)

        const timelapseRaw = readFileSync(tempPathShort)

        unlinkSync(tempPathShort)

        return timelapseRaw
    }
Example #27
Source File: util.ts    From attranslate with MIT License 6 votes vote down vote up
export function writeUtf8File(path: string, content: string) {
  writeFileSync(path, content, { encoding: "utf8" });
}
Example #28
Source File: mock-creators.ts    From playwright-fluent with MIT License 6 votes vote down vote up
export function generateCodeForMissingMock(
  missingMock: MissingMock,
  targetDirectory: string,
): void {
  ensureDirectoryExists(targetDirectory);
  const targetFolderName = urlToShortPath(missingMock.url).replace(/\//g, '_').replace(/\?/g, '#');
  const targetSubDirectory = path.join(targetDirectory, targetFolderName);
  ensureDirectoryExists(targetSubDirectory);
  switch (missingMock.mimeType) {
    case 'application/json':
      {
        const dataFileName = `${targetFolderName}.json`;
        const dataFilePath = path.join(targetSubDirectory, dataFileName);
        writeFileSync(dataFilePath, JSON.stringify(missingMock.response, null, 2));
        const mockSourceCode = generateMockCodeOf(missingMock, dataFileName);
        writeFileSync(path.join(targetSubDirectory, `${targetFolderName}.ts`), mockSourceCode);
      }
      break;

    default:
      // eslint-disable-next-line no-console
      console.log(`Unsupported mime type: ${missingMock.mimeType}`);
      break;
  }
}
Example #29
Source File: UserSettings.ts    From viewer with MIT License 6 votes vote down vote up
/**
   * Write the settings.json file to user's app data directory
   */
  private _writeSettings() {
    writeFileSync(
      join(this.dataPath, "settings.json"),
      JSON.stringify(this.settings)
    );
  }