fs#readFileSync TypeScript Examples

The following examples show how to use fs#readFileSync. 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 programmer-fa with MIT License 8 votes vote down vote up
loadJSONFileContent = (filePath: string): string[] | Error => {
  let fileContent: string;

  if (!isFileJSON(filePath)) {
    return new Error('File is not JSON');
  }

  try {
    fileContent = readFileSync(filePath, 'utf8');
  } catch (e) {
    return new Error(e);
  }

  fileContent = JSON.parse(fileContent);

  return Array.isArray(fileContent) ? fileContent : new Error('File doesn\'t include an array');
}
Example #2
Source File: breakpointHandler.ts    From vscode-autohotkey with MIT License 6 votes vote down vote up
public buildBreakPoint(path: string, sourceBreakpoints: DebugProtocol.SourceBreakpoint[], callback: Callback): DebugProtocol.Breakpoint[] {

        if (!existsSync(path)) {
            return [];
        }
        const sourceLines = readFileSync(path).toString().split('\n');
        const bps = sourceBreakpoints.map((sourceBreakpoint) => {
            const breakPoint = new Breakpoint(false, sourceBreakpoint.line, sourceBreakpoint.column, new Source(basename(path), path))
            const lineText = sourceLines[sourceBreakpoint.line];
            if (lineText && lineText.trim().charAt(0) != ';') {
                breakPoint.verified = true;
            }
            callback(breakPoint)
            return breakPoint;
        })
        this._breakPoints.set(path, bps)
        return bps;
    }
Example #3
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 #4
Source File: index.ts    From vt-api with GNU Affero General Public License v3.0 6 votes vote down vote up
function saveChannel(filename: string, dry = false, save = true, async = false) {
  const groupName = filename.slice(0, -5);
  const channelList: MemberObject[] = JSON.parse(readFileSync(`${ROOT_DIR}/${filename}`, 'utf-8'));
  const parseChannel = (channel: MemberObject): any => { channel.organization = groupName; return channel; };
  const parsedChannels: MemberObject[] = channelList.map(parseChannel);
  if (dry) return parsedChannels;
  if (save) {
    const writeOp = Members
      .create(<any[]>parsedChannels)
      .then(() => logger.info(`${filename} OK`))
      .catch(err => logger.error(`${filename} CODE: ${err.code}`, err?.keyValue ?? ''));
    if (async) return writeOp;
  }
  return channelList.map((channel): BasicChannelData => [channel.channel_id, groupName, channel.platform_id]);
}
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: schematic.ts    From nx-plugins with MIT License 6 votes vote down vote up
function mergePulumiProjectIntoTree(adapter: BaseAdapter) {
  return (host: Tree) => {
    const infraDir = join(adapter.project.root, 'infrastructure');

    const PulumiFile = join(infraDir, 'Pulumi.yaml');
    const pulumiContent = readFileSync(PulumiFile);
    unlinkSync(PulumiFile);
    host.create(PulumiFile, pulumiContent);

    return host;
  };
}
Example #7
Source File: index.ts    From a18n with MIT License 6 votes vote down vote up
getFileList = (path: string | undefined): string[] | undefined => {
  if (path) {
    return getFiles(path, { exclude: args.exclude }).filter(isSourceCode)
  }
  return !isTTY
    ? readFileSync(0, 'utf-8')
        .split('\n')
        .filter(Boolean)
        .map((f) => f.trim())
    : undefined
}
Example #8
Source File: storage-test-contract.test.ts    From fuels-ts with Apache License 2.0 6 votes vote down vote up
setup = async () => {
  const provider = new Provider('http://127.0.0.1:4000/graphql');
  // Create wallet
  const wallet = await TestUtils.generateTestWallet(provider, [[1_000, NativeAssetId]]);

  // Deploy contract
  const bytecode = readFileSync(join(__dirname, './out/debug/storage-test.bin'));
  const factory = new ContractFactory(bytecode, abi, wallet);
  const contract = await factory.deployContract();

  return contract;
}
Example #9
Source File: index.ts    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
export async function createServer(schemaPath: any, mockRest = true, allowInvalidCreds = true) {
  let typeDefs
  try {
    typeDefs = await readFileSync(schemaPath).toString('utf-8');
  } catch (ex) {
    throw new Error(`Unable to read ${schemaPath}, please specify correct path to grapqhl schema file using --schema option`)
  }

  const expressApp = express();
  
  const apolloServer = new ApolloServer({
    typeDefs,
    mocks,
    resolvers: mockedResolvers(gql`${typeDefs}`),
    mockEntireSchema: false
  });
  await apolloServer.start();

  apolloServer.applyMiddleware({app: expressApp});
  expressApp.use(express.urlencoded({extended: false}), express.json())
  expressApp.use(createOauthRouter(allowInvalidCreds))
  if (mockRest) {
    expressApp.use(restRouter)
  }

  return {expressApp, apolloServer};
}
Example #10
Source File: vite.config.ts    From nest-react with GNU Lesser General Public License v3.0 6 votes vote down vote up
// Commit information to identify the build
function getBuildId(): string {
  try {
    const versionPath = join(__dirname, '..', '..', 'VERSION');
    const versionData = readFileSync(versionPath)
      .toString()
      .split(/[\r\n]+/);
    const [, branch] = versionData
      .find(line => line.includes('GIT_BRANCH'))!
      .split('=');
    const [, shortHash] = versionData
      .find(line => line.includes('GIT_SHORT_HASH'))!
      .split('=');
    return `${shortHash}@${branch}`;
  } catch (err) {
    console.log(err);
    return 'no-git';
  }
}
Example #11
Source File: json-signer.ts    From pix-qrcode-utils with MIT License 6 votes vote down vote up
static async readPFX( filePath: string, passphrase: string ) {
    const result = new Promise<Key>( (resolve, reject) => {
      readPkcs12(
        readFileSync( filePath ),
        { p12Password: passphrase },
        (err,pfx) => {
          if ( err ) {
            reject( err );
          }

          let k: Key = asKey( pfx.key )

          resolve( k );
        }
      );
    });

    return result;
  }
Example #12
Source File: event-store.service.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
private extractProjectionContent(projection: EventStoreProjection): string {
    let content;
    if (projection.content) {
      this.logger.log(`"${projection.name}" projection in content`);
      content = projection.content;
    } else if (projection.file) {
      this.logger.log(`"${projection.name}" projection in file`);
      content = readFileSync(projection.file, 'utf8');
    }
    return content;
  }
Example #13
Source File: generate-runtimes-body.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
function getRuntimeInfo(srtoolReportFolder: string, runtimeName: string) {
  const specVersion = execSync(
    `cat ../runtime/${runtimeName}/src/lib.rs | grep 'spec_version: [0-9]*' | tail -1`
  ).toString();
  return {
    name: runtimeName,
    version: /:\s?([0-9A-z\-]*)/.exec(specVersion)[1],
    srtool: JSON.parse(
      readFileSync(path.join(srtoolReportFolder, `./${runtimeName}-srtool-digest.json`)).toString()
    ),
  };
}
Example #14
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 #15
Source File: spParser.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
export function parseFile(
  file: string,
  items: FileItems,
  itemsRepository: ItemsRepository,
  searchTokens: boolean,
  IsBuiltIn: boolean
) {
  if (!existsSync(file)) {
    return;
  }
  let data = readFileSync(file, "utf-8");

  // Test for symbolic links
  let match = data.match(/^(?:\.\.\/)+(?:[\/\w\-])+\.\w+/);
  if (match !== null) {
    let folderpath = dirname(file);
    file = resolve(folderpath, match[0]);
    data = readFileSync(file, "utf-8");
  }
  parseText(data, file, items, itemsRepository, searchTokens, IsBuiltIn);
}
Example #16
Source File: submit-feed.test.ts    From amazon-mws-api-sdk with MIT License 6 votes vote down vote up
describe(`submit-feed`, () => {
  const feeds = new Feeds(httpClient)

  it('should be able to submit sample feed', async () => {
    expect.assertions(1)

    const parameters: SubmitFeedParameters = {
      FeedContent: readFileSync(path.join(__dirname, `/submit_feed_sample_feed_content.xml`), {
        encoding: 'utf8',
      }),
      FeedType: '_POST_PRODUCT_DATA_',
    }

    const [response] = await feeds.submitFeed(parameters)

    expect(response).toBeDefined()
  })
})
Example #17
Source File: forge.ts    From WebCord with MIT License 6 votes vote down vote up
// Some custom functions

function getCommit():string | void {
  const refsPath = readFileSync(resolve(projectPath, '.git/HEAD'))
    .toString()
    .split(': ')[1]
    ?.trim();
  if(refsPath) return readFileSync(resolve(projectPath, '.git', refsPath)).toString().trim();
}
Example #18
Source File: Options.ts    From tf2autobot with MIT License 6 votes vote down vote up
function lintPath(filepath: string): void {
    const rawOptions = readFileSync(filepath, { encoding: 'utf8' });
    try {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
        jsonlint.parse(rawOptions);
    } catch (e) {
        throwLintError(filepath, e as Error);
    }
}
Example #19
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 #20
Source File: utils.ts    From HomebridgeMagicHome-DynamicPlatform with Apache License 2.0 6 votes vote down vote up
export function loadJson<T>(file: string, replacement: T): T {
  if (!existsSync(file)) {
    return replacement;
  }
  return parseJson<T>(readFileSync(file).toString(), replacement);
}
Example #21
Source File: config.ts    From rewind with MIT License 6 votes vote down vote up
export function readRewindElectronSettings(configPath: string) {
  const file = join(configPath, REWIND_CFG_NAME);
  let json;
  try {
    const str = readFileSync(file, "utf-8");
    json = JSON.parse(str);
  } catch (e) {
    console.warn("Could not parse the config correctly:\n" + e);
    return DEFAULT_REWIND_ELECTRON_SETTINGS;
  }
  if (!validate(json)) {
    console.warn(
      "Could not validate the config JSON correctly. Do not modify the file if you are not sure what you are doing.",
    );
    return DEFAULT_REWIND_ELECTRON_SETTINGS;
  }
  return json;
}
Example #22
Source File: process-docs.ts    From beacon-sdk with MIT License 6 votes vote down vote up
updateFile = (filename: string) => {
  const content = readFileSync(filename, 'utf8')

  const newContent = content
    .split(`<label class="tsd-widget" for="tsd-filter-externals">Externals</label>`)
    .join(`<label class="tsd-widget" for="tsd-filter-externals">Internal Definitions</label>`)

  writeFileSync(filename, addJs(newContent), { encoding: 'utf8' })
}
Example #23
Source File: getDiagnostics.ts    From typescript-strict-plugin with MIT License 6 votes vote down vote up
export async function getDiagnostics(projectPath: string, filePath: string) {
  const server = new TSServer();

  const file = resolve(projectPath, filePath);

  const fileContent = readFileSync(file, 'utf-8');

  server.send({ command: 'open', arguments: { file, fileContent, scriptKindName: 'TS' } });

  await server.waitEvent('projectLoadingFinish');

  server.send({ command: 'geterr', arguments: { files: [file], delay: 0 } });

  await server.waitEvent('semanticDiag');

  await server.close();

  const semanticDiagEvent = findResponse(server.responses, 'semanticDiag');

  return semanticDiagEvent?.body.diagnostics;
}
Example #24
Source File: addEnv.ts    From setup-cpp with Apache License 2.0 6 votes vote down vote up
/// handles adding conditions to source .cpprc file from .bashrc and .profile
export function setupCppInProfile() {
  if (setupCppInProfile_called) {
    return
  }

  // a variable that prevents source_cpprc from being called from .bashrc and .profile
  const source_cpprc_str = "export SOURCE_CPPRC=0"

  if (existsSync(cpprc_path)) {
    const cpprc_content = readFileSync(cpprc_path, "utf8")
    if (cpprc_content.includes(source_cpprc_str)) {
      // already executed setupCppInProfile
      return
    }
  }

  appendFileSync(cpprc_path, `\n${source_cpprc_str}\n`)
  info(`Added ${source_cpprc_str} to ${cpprc_path}`)

  const source_cpprc_string = `\n# source .cpprc if SOURCE_CPPRC is not set to 0\nif [[ "$SOURCE_CPPRC" != 0 && -f "${cpprc_path}" ]]; then source "${cpprc_path}"; fi\n`

  try {
    // source cpprc in .profile
    const profile_path = untildify(".profile")
    appendFileSync(profile_path, source_cpprc_string)
    info(`${source_cpprc_string} was added to ${profile_path}`)

    // source cpprc in .bashrc too
    const bashrc_path = untildify(".bashrc")
    appendFileSync(bashrc_path, source_cpprc_string)
    info(`${source_cpprc_string} was added to ${bashrc_path}`)
  } catch (err) {
    warning(`Failed to add ${source_cpprc_string} to .profile or .bashrc. You should add it manually: ${err}`)
  }

  setupCppInProfile_called = true
}
Example #25
Source File: validation.test.ts    From airnode with MIT License 6 votes vote down vote up
describe('config validation', () => {
  const exampleConfigPath = join(__dirname, '../../config/config.example.json');
  const exampleSecrets = dotenv.parse(readFileSync(join(__dirname, '../../config/secrets.example.env')));

  it('loads the config without validation', () => {
    const notThrowingFunction = () => loadTrustedConfig(exampleConfigPath, exampleSecrets);
    expect(notThrowingFunction).not.toThrow();
  });

  it('loads the config with validation and fails because the config is invalid', async () => {
    const invalidConfig = JSON.parse(readFileSync(exampleConfigPath, 'utf-8'));
    invalidConfig.nodeSettings.nodeVersion = '0.4.0';
    mockReadFileSync('config.example.json', JSON.stringify(invalidConfig));

    const throwingFunction = () => loadConfig(exampleConfigPath, exampleSecrets);

    const issues = [
      {
        code: 'custom',
        message: `The "nodeVersion" must be ${packageVersion}`,
        path: ['nodeSettings', 'nodeVersion'],
      },
    ];
    const expectedError = new Error(`Invalid Airnode configuration file: ${JSON.stringify(issues, null, 2)}`);
    expect(throwingFunction).toThrow(expectedError);
  });
});
Example #26
Source File: generateDiff.spec.ts    From diff with Apache License 2.0 6 votes vote down vote up
describe('Diff', () => {
  test('Check if diff is an empty array for same inputs', () => {
    expect(generateDiff(firstDocument, firstDocument)).toStrictEqual([]);
  });

  test('Check diff output with local inputs', () => {
    expect(generateDiff(firstDocument, secondDocument)).toStrictEqual(
      diffLocalOutput
    );
  });

  test('Check diff output through parser with no difference', async () => {
    const specDocument = readFileSync(
      resolve('./test/spec/asyncapi.yml'),
      'utf-8'
    );
    const firstDocument = await parse(specDocument);
    expect(
      generateDiff(firstDocument.json(), firstDocument.json())
    ).toStrictEqual([]);
  });

  test('Check diff output through parser with difference input', async () => {
    const firstSpecDocument = readFileSync(
      resolve('./test/spec/asyncapi.yml'),
      'utf-8'
    );
    const secondSpecDocument = readFileSync(
      resolve('./test/spec/diffSpec.yml'),
      'utf-8'
    );
    const firstDocument = await parse(firstSpecDocument);
    const secondDocument = await parse(secondSpecDocument);
    expect(
      generateDiff(firstDocument.json(), secondDocument.json())
    ).toStrictEqual(diffOutput);
  });
});
Example #27
Source File: configure-codegen.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export async function testConfigureCodegen(config: AmplifyFrontendConfig, projectRoot: string, schema: string) {
    // init project and add API category
    await initProjectWithProfile(projectRoot, { ...config });
    const projectName = createRandomName();
    await addApiWithoutSchema(projectRoot, { apiName: projectName });
    await updateApiSchema(projectRoot, projectName, schema);

    const userSourceCodePath = testSetupBeforeAddCodegen(projectRoot, config);

    // add codegen succeeds
    await expect(addCodegen(projectRoot, { ...config })).resolves.not.toThrow();

    const addedCodegenConfiguration = readFileSync(getGraphQLConfigFilePath(projectRoot)).toString();

    // update codegen configuration
    const settings = { isCodegenConfigured: true, maxStatementDepth: 4, ...config };
    await expect(configureCodegen(projectRoot, settings)).resolves.not.toThrow();

    // pre-existing file should still exist
    expect(existsSync(userSourceCodePath)).toBe(true);
    // previously generated files should still exist
    expect(isNotEmptyDir(path.join(projectRoot, config.graphqlCodegenDir))).toBe(true);

    // graphql configuration should be updated to with MaxStatementDepth=4
    testValidGraphQLConfig(projectRoot, config, 4, true);
    const updatedCodegenConfiguration = readFileSync(getGraphQLConfigFilePath(projectRoot)).toString();
    // the codegen configuration is updated
    expect(addedCodegenConfiguration).not.toMatch(updatedCodegenConfiguration);
}
Example #28
Source File: aws-image-builder-stack.ts    From amazon-ec2-image-builder-samples with MIT No Attribution 6 votes vote down vote up
getData = (dir: string, file: string) => {
    const filePath = path.join(__dirname, "..", dir, file);
    if (!existsSync(filePath)) {
      Annotations.of(this).addError(
        `Component file ${filePath} does not exists`
      );
      return "";
    }
    return readFileSync(path.join(__dirname, "..", dir, file)).toString();
  };
Example #29
Source File: artifact.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Read the ABI and bytecode for the contract `contractName` from the ABI and bytecode files.
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function readContractABIAndBytecode(task: Task, contractName: string): { abi: any; bytecode: string } {
  // Read contract ABI from file
  const abiFilePath = path.resolve(task.dir(), 'abi', `${contractName}.json`);
  const abiFileExists = existsSync(abiFilePath) && statSync(abiFilePath).isFile();
  const abi = abiFileExists ? JSON.parse(readFileSync(abiFilePath).toString()) : [];

  // Read contract bytecode from file
  const bytecodeFilePath = path.resolve(task.dir(), 'bytecode', `${contractName}.json`);
  const bytecodeFileExists = existsSync(bytecodeFilePath) && statSync(bytecodeFilePath).isFile();
  const bytecode = bytecodeFileExists ? JSON.parse(readFileSync(bytecodeFilePath).toString()).creationCode : '';
  return { abi, bytecode };
}