本文整理汇总了TypeScript中fs.readFileSync函数的典型用法代码示例。如果您正苦于以下问题:TypeScript readFileSync函数的具体用法?TypeScript readFileSync怎么用?TypeScript readFileSync使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了readFileSync函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1:
import * as fs from "fs";
let input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n");
const n = +input[0];
const [d, x] = input[1].split(" ").map((x: string): number => +x);
const a: Array<number> = [];
for (let i = 0; i < n; i++) {
a.push(+input[i + 2]);
}
let sum = x;
for (const delta of a) {
sum += 1 + Math.floor((d - 1) / delta);
}
console.log(sum);
示例2: readFileContents
function readFileContents(testCase: string, fileName: string): string
{
const fullFileName = getCaseFileName(testCase, fileName);
return fs.readFileSync(fullFileName).toString();
}
示例3: _renderUniversal
async function _renderUniversal(
options: BuildWebpackAppShellSchema,
context: BuilderContext,
browserResult: BrowserBuilderOutput,
serverResult: ServerBuilderOutput,
): Promise<BrowserBuilderOutput> {
const browserIndexOutputPath = path.join(browserResult.outputPath || '', 'index.html');
const indexHtml = fs.readFileSync(browserIndexOutputPath, 'utf8');
const serverBundlePath = await _getServerModuleBundlePath(options, context, serverResult);
const root = context.workspaceRoot;
requireProjectModule(root, 'zone.js/dist/zone-node');
const renderModuleFactory = requireProjectModule(
root,
'@angular/platform-server',
).renderModuleFactory;
const AppServerModuleNgFactory = require(serverBundlePath).AppServerModuleNgFactory;
const outputIndexPath = options.outputIndexPath
? path.join(root, options.outputIndexPath)
: browserIndexOutputPath;
// Render to HTML and overwrite the client index file.
const html = await renderModuleFactory(AppServerModuleNgFactory, {
document: indexHtml,
url: options.route,
});
fs.writeFileSync(outputIndexPath, html);
const browserTarget = targetFromTargetString(options.browserTarget);
const rawBrowserOptions = await context.getTargetOptions(browserTarget);
const browserBuilderName = await context.getBuilderNameForTarget(browserTarget);
const browserOptions = await context.validateOptions<JsonObject & BrowserBuilderSchema>(
rawBrowserOptions,
browserBuilderName,
);
if (browserOptions.serviceWorker) {
const host = new NodeJsSyncHost();
// Create workspace.
const registry = new schema.CoreSchemaRegistry();
registry.addPostTransform(schema.transforms.addUndefinedDefaults);
const workspace = await experimental.workspace.Workspace.fromPath(
host,
normalize(context.workspaceRoot),
registry,
);
const projectName = context.target ? context.target.project : workspace.getDefaultProjectName();
if (!projectName) {
throw new Error('Must either have a target from the context or a default project.');
}
const projectRoot = resolve(
workspace.root,
normalize(workspace.getProject(projectName).root),
);
await augmentAppWithServiceWorker(
host,
normalize(root),
projectRoot,
join(normalize(root), browserOptions.outputPath),
browserOptions.baseHref || '/',
browserOptions.ngswConfigPath,
);
}
return browserResult;
}
示例4: runTest
export function runTest(testDirectory: string, rulesDirectory?: string | string[]): TestResult {
const filesToLint = glob.sync(path.join(testDirectory, `**/*${MARKUP_FILE_EXTENSION}`));
const tslintConfig = Linter.findConfiguration(path.join(testDirectory, "tslint.json"), "").results;
const tsConfig = path.join(testDirectory, "tsconfig.json");
let compilerOptions: ts.CompilerOptions = { allowJs: true };
const hasConfig = fs.existsSync(tsConfig);
if (hasConfig) {
const {config, error} = ts.readConfigFile(tsConfig, ts.sys.readFile);
if (error !== undefined) {
throw new Error(JSON.stringify(error));
}
const parseConfigHost = {
fileExists: fs.existsSync,
readDirectory: ts.sys.readDirectory,
readFile: (file: string) => fs.readFileSync(file, "utf8"),
useCaseSensitiveFileNames: true,
};
compilerOptions = ts.parseJsonConfigFileContent(config, parseConfigHost, testDirectory).options;
}
const results: TestResult = { directory: testDirectory, results: {} };
for (const fileToLint of filesToLint) {
const isEncodingRule = path.basename(testDirectory) === "encoding";
const fileCompileName = denormalizeWinPath(path.resolve(fileToLint.replace(/\.lint$/, "")));
let fileText = isEncodingRule ? readBufferWithDetectedEncoding(fs.readFileSync(fileToLint)) : fs.readFileSync(fileToLint, "utf-8");
const tsVersionRequirement = parse.getTypescriptVersionRequirement(fileText);
if (tsVersionRequirement !== undefined) {
const tsVersion = new semver.SemVer(ts.version);
// remove prerelease suffix when matching to allow testing with nightly builds
if (!semver.satisfies(`${tsVersion.major}.${tsVersion.minor}.${tsVersion.patch}`, tsVersionRequirement)) {
results.results[fileToLint] = {
requirement: tsVersionRequirement,
skipped: true,
};
continue;
}
// remove the first line from the file before continuing
const lineBreak = fileText.search(/\n/);
fileText = lineBreak === -1 ? "" : fileText.substr(lineBreak + 1);
}
const fileTextWithoutMarkup = parse.removeErrorMarkup(fileText);
const errorsFromMarkup = parse.parseErrorsFromMarkup(fileText);
let program: ts.Program | undefined;
if (hasConfig) {
const compilerHost: ts.CompilerHost = {
fileExists: (file) => file === fileCompileName || fs.existsSync(file),
getCanonicalFileName: (filename) => filename,
getCurrentDirectory: () => process.cwd(),
getDefaultLibFileName: () => ts.getDefaultLibFileName(compilerOptions),
getDirectories: (dir) => fs.readdirSync(dir),
getNewLine: () => "\n",
getSourceFile(filenameToGet) {
const target = compilerOptions.target === undefined ? ts.ScriptTarget.ES5 : compilerOptions.target;
if (filenameToGet === ts.getDefaultLibFileName(compilerOptions)) {
const fileContent = fs.readFileSync(ts.getDefaultLibFilePath(compilerOptions), "utf8");
return ts.createSourceFile(filenameToGet, fileContent, target);
} else if (denormalizeWinPath(filenameToGet) === fileCompileName) {
return ts.createSourceFile(filenameToGet, fileTextWithoutMarkup, target, true);
}
const text = fs.readFileSync(filenameToGet, "utf8");
return ts.createSourceFile(filenameToGet, text, target, true);
},
readFile: (x) => x,
useCaseSensitiveFileNames: () => true,
writeFile: () => null,
};
program = ts.createProgram([fileCompileName], compilerOptions, compilerHost);
}
const lintOptions = {
fix: false,
formatter: "prose",
formattersDirectory: "",
rulesDirectory,
};
const linter = new Linter(lintOptions, program);
// Need to use the true path (ending in '.lint') for "encoding" rule so that it can read the file.
linter.lint(isEncodingRule ? fileToLint : fileCompileName, fileTextWithoutMarkup, tslintConfig);
const failures = linter.getResult().failures;
const errorsFromLinter: LintError[] = failures.map((failure) => {
const startLineAndCharacter = failure.getStartPosition().getLineAndCharacter();
const endLineAndCharacter = failure.getEndPosition().getLineAndCharacter();
return {
endPos: {
col: endLineAndCharacter.character,
line: endLineAndCharacter.line,
},
message: failure.getFailure(),
startPos: {
col: startLineAndCharacter.character,
line: startLineAndCharacter.line,
},
};
});
//.........这里部分代码省略.........
示例5: parseTorrent
// magnet uri with torrent name
parseTorrent('magnet:?xt=urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36&dn=Leaves%20of%20Grass%20by%20Walt%20Whitman.epub')
// { xt: 'urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36',
// dn: 'Leaves of Grass by Walt Whitman.epub',
// infoHash: 'd2474e86c95b19b8bcfdb92bc12c9d44667cfa36',
// name: 'Leaves of Grass by Walt Whitman.epub' }
// magnet uri with trackers
parseTorrent('magnet:?xt=urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36&tr=http%3A%2F%2Ftracker.example.com%2Fannounce')
// { xt: 'urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36',
// tr: 'http://tracker.example.com/announce',
// infoHash: 'd2474e86c95b19b8bcfdb92bc12c9d44667cfa36',
// announce: [ 'http://tracker.example.com/announce' ] }
// .torrent file (as a Buffer)
parseTorrent(fs.readFileSync(__dirname + '/torrents/leaves.torrent'))
// { info:
// { length: 362017,
// name: <Buffer 4c 65 61 76 65 73 20 6f 66 20 47 72 61 73 73 20 62 79 20 57 61 6c 74 20 57 68 69 74 6d 61 6e 2e 65 70 75 62>,
// 'piece length': 16384,
// pieces: <Buffer 1f 9c 3f 59 be ec 07 97 15 ec 53 32 4b de 85 69 e4 a0 b4 eb ec 42 30 7d 4c e5 55 7b 5d 39 64 c5 ef 55 d3 54 cf 4a 6e cc 7b f1 bc af 79 d1 1f a5 e0 be 06 ...> },
// infoBuffer: <Buffer 64 36 3a 6c 65 6e 67 74 68 69 33 36 32 30 31 37 65 34 3a 6e 61 6d 65 33 36 3a 4c 65 61 76 65 73 20 6f 66 20 47 72 61 73 73 20 62 79 20 57 61 6c 74 20 57 ...>,
// infoHash: 'd2474e86c95b19b8bcfdb92bc12c9d44667cfa36',
// name: 'Leaves of Grass by Walt Whitman.epub',
// private: false,
// created: Thu Aug 01 2013 06:27:46 GMT-0700 (PDT),
// comment: 'Downloaded from http://TheTorrent.org',
// announce:
// [ 'http://tracker.example.com/announce' ],
// urlList: [],
// files:
示例6: getExtractor
function getExtractor(fileName: string, password?: string) {
let buf = fs.readFileSync(`./testFiles/${fileName}`);
let arrBuf = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
return unrar.createExtractorFromData(arrBuf, password);
}
示例7: _getFile
private _getFile(): any {
const contents = fs.readFileSync(this.p, 'utf8');
return JSON.parse(contents);
}
示例8: require
require('source-map-support').install()
import * as Db from '../lib/db-lmdb'
import * as fs from 'fs'
let settings = JSON.parse(fs.readFileSync("settings.json", 'utf8'))
console.log('storage', settings.storage)
let db = new Db.Db(settings.storage)
let email = process.argv[2]
if (email) {
console.log('user dump', email)
db.connect(async () => {
let user
try {
user = await db.find_user_by({ email: email })
} catch (e) {
try {
user = await db.find_user_by({ username: email })
} catch (e) {
}
}
if (user) {
console.log(JSON.stringify(user, null, 2))
let friending = await db.friending_me(user.id)
console.log(user.friends.length, 'friends', friending.length, 'friending')
} else {
console.log(email, 'not found')
}
})
} else {
示例9: constructor
"Do unto others as you would have them do unto you.",
assert.ifError);
fs.write(1234, "test");
fs.writeFile("Harry Potter",
"\"You be wizzing, Harry,\" jived Dumbledore.",
{
encoding: "ascii"
},
assert.ifError);
var content: string,
buffer: Buffer;
content = fs.readFileSync('testfile', 'utf8');
content = fs.readFileSync('testfile', {encoding : 'utf8'});
buffer = fs.readFileSync('testfile');
buffer = fs.readFileSync('testfile', {flag : 'r'});
fs.readFile('testfile', 'utf8', (err, data) => content = data);
fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data);
fs.readFile('testfile', (err, data) => buffer = data);
fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data);
class Networker extends events.EventEmitter {
constructor() {
super();
this.emit("mingling");
}
}
示例10: function
QUnit.test("extract multline tag text", function () {
var comments: d2t.DocComment[] = new d2t.Parser(fs.readFileSync("test/fixtures/comment2.js", 'utf8')).exec();
QUnit.scapeEqual(comments[0].tags[1].text, '{String} desc A description of the assertion. This will become\r\n\
the text of the Error thrown if the assertion fails.');
});