本文整理汇总了TypeScript中fs.statSync函数的典型用法代码示例。如果您正苦于以下问题:TypeScript statSync函数的具体用法?TypeScript statSync怎么用?TypeScript statSync使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了statSync函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: checkForProblems
export function checkForProblems():verification{
//Give some default values
let results:verification = {
isValidOS: false,
folderIsOpen: false,
folderPath: '',
iisExists:false,
programPath: ''
};
// *******************************************
// Check if we are on Windows and not OSX
// *******************************************
//Type = 'WINDOWS_NT'
let operatingSystem = os.type();
//Uppercase string to ensure we match correctly
operatingSystem = operatingSystem.toUpperCase();
//New ES2015 includes as opposed to indexOf()
if(!operatingSystem.includes('WINDOWS_NT')){
vscode.window.showErrorMessage('You can only run this extension on Windows.');
results.isValidOS = false;
}
else {
//Is Valid & Passes - we are on Windows
results.isValidOS = true;
}
// *******************************************
// Checks that VS Code is open with a folder
// *******************************************
//Get the path of the folder that is open in VS Code
const folderPath = vscode.workspace.rootPath;
//Check if we are in a folder/workspace & NOT just have a single file open
if(!folderPath){
vscode.window.showErrorMessage('Please open a workspace directory first.');
//We are not a folder
results.folderIsOpen = false;
results.folderPath = null;
}
else {
results.folderIsOpen = true;
results.folderPath = folderPath;
}
// *******************************************
// Verify IIS Express excutable Exists
// *******************************************
//Let's check for two folder locations for IISExpress
//32bit machines - 'C:\Program Files\IIS Express\iisexpress.exe'
//64bit machines - 'C:\Program Files (x86)\IIS Express\iisexpress.exe'
//'C:\Program Files (x86)'
let programFilesPath = process.env.ProgramFiles;
//Try to find IISExpress excutable - build up path to EXE
programFilesPath = path.join(programFilesPath, 'IIS Express', 'iisexpress.exe');
try {
//Check if we can find the file path (get stat info on it)
let fileCheck = fs.statSync(programFilesPath);
results.iisExists = true;
results.programPath = programFilesPath;
}
catch (err) {
//ENOENT - File or folder not found
if(err && err.code.toUpperCase() === 'ENOENT'){
vscode.window.showErrorMessage(`We did not find a copy of IISExpress.exe at ${programFilesPath}`);
}
else if(err){
//Some other error - maybe file permission or ...?
vscode.window.showErrorMessage(`There was an error trying to find IISExpress.exe at ${programFilesPath} due to ${err.message}`);
}
results.iisExists = false;
results.programPath = null;
}
//Return an object back from verifications
return results;
}
示例2: statSync
const getCommonMode = (path: string) =>
statSync(path)
.mode.toString(8)
.slice(-3);
示例3: parseInt
const isNotWritable = (fileOrDir: string) => {
const mode = fs.statSync(fileOrDir).mode;
// tslint:disable-next-line: no-bitwise
return !(mode & parseInt('222', 8));
};
示例4: File
.map(filePath => new File({
path: filePath,
stat: fs.statSync(filePath),
base: extensionPath,
contents: fs.createReadStream(filePath) as any
}));
示例5: main
export async function main(argv: string[]): Promise<any> {
let args: ParsedArgs;
try {
args = parseCLIProcessArgv(argv);
} catch (err) {
console.error(err.message);
return TPromise.as(null);
}
// Help
if (args.help) {
console.log(buildHelpMessage(product.nameLong, product.applicationName, pkg.version));
}
// Version Info
else if (args.version) {
console.log(`${pkg.version}\n${product.commit}\n${process.arch}`);
}
// Extensions Management
else if (shouldSpawnCliProcess(args)) {
const mainCli = new TPromise<IMainCli>(c => require(['vs/code/node/cliProcessMain'], c));
return mainCli.then(cli => cli.main(args));
}
// Write File
else if (args['file-write']) {
const source = args._[0];
const target = args._[1];
// Validate
if (
!source || !target || source === target || // make sure source and target are provided and are not the same
!paths.isAbsolute(source) || !paths.isAbsolute(target) || // make sure both source and target are absolute paths
!fs.existsSync(source) || !fs.statSync(source).isFile() || // make sure source exists as file
!fs.existsSync(target) || !fs.statSync(target).isFile() // make sure target exists as file
) {
return TPromise.wrapError(new Error('Using --file-write with invalid arguments.'));
}
try {
// Check for readonly status and chmod if so if we are told so
let targetMode: number;
let restoreMode = false;
if (!!args['file-chmod']) {
targetMode = fs.statSync(target).mode;
if (!(targetMode & 128) /* readonly */) {
fs.chmodSync(target, targetMode | 128);
restoreMode = true;
}
}
// Write source to target
const data = fs.readFileSync(source);
if (isWindows) {
// On Windows we use a different strategy of saving the file
// by first truncating the file and then writing with r+ mode.
// This helps to save hidden files on Windows
// (see https://github.com/Microsoft/vscode/issues/931) and
// prevent removing alternate data streams
// (see https://github.com/Microsoft/vscode/issues/6363)
fs.truncateSync(target, 0);
writeFileAndFlushSync(target, data, { flag: 'r+' });
} else {
writeFileAndFlushSync(target, data);
}
// Restore previous mode as needed
if (restoreMode) {
fs.chmodSync(target, targetMode);
}
} catch (error) {
return TPromise.wrapError(new Error(`Using --file-write resulted in an error: ${error}`));
}
return TPromise.as(null);
}
// Just Code
else {
const env = assign({}, process.env, {
'VSCODE_CLI': '1', // this will signal Code that it was spawned from this module
'ELECTRON_NO_ATTACH_CONSOLE': '1'
});
delete env['ELECTRON_RUN_AS_NODE'];
const processCallbacks: ((child: ChildProcess) => Thenable<any>)[] = [];
const verbose = args.verbose || args.status || typeof args['upload-logs'] !== 'undefined';
if (verbose) {
env['ELECTRON_ENABLE_LOGGING'] = '1';
processCallbacks.push(child => {
child.stdout.on('data', (data: Buffer) => console.log(data.toString('utf8').trim()));
child.stderr.on('data', (data: Buffer) => console.log(data.toString('utf8').trim()));
return new TPromise<void>(c => child.once('exit', () => c(null)));
//.........这里部分代码省略.........
示例6:
.filter((name)=>fs.statSync(path + '/' + name).isDirectory());
示例7: getFilesize
/** Returns the size of a file in kilobytes. */
function getFilesize(filePath: string) {
return statSync(filePath).size / 1000;
}
示例8: getNodeSystem
function getNodeSystem(): System {
const _fs = require("fs");
const _path = require("path");
const _os = require("os");
const _tty = require("tty");
// average async stat takes about 30 microseconds
// set chunk size to do 30 files in < 1 millisecond
function createWatchedFileSet(interval = 2500, chunkSize = 30) {
let watchedFiles: WatchedFile[] = [];
let nextFileToCheck = 0;
let watchTimer: any;
function getModifiedTime(fileName: string): Date {
return _fs.statSync(fileName).mtime;
}
function poll(checkedIndex: number) {
const watchedFile = watchedFiles[checkedIndex];
if (!watchedFile) {
return;
}
_fs.stat(watchedFile.fileName, (err: any, stats: any) => {
if (err) {
watchedFile.callback(watchedFile.fileName);
}
else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) {
watchedFile.mtime = getModifiedTime(watchedFile.fileName);
watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0);
}
});
}
// this implementation uses polling and
// stat due to inconsistencies of fs.watch
// and efficiency of stat on modern filesystems
function startWatchTimer() {
watchTimer = setInterval(() => {
let count = 0;
let nextToCheck = nextFileToCheck;
let firstCheck = -1;
while ((count < chunkSize) && (nextToCheck !== firstCheck)) {
poll(nextToCheck);
if (firstCheck < 0) {
firstCheck = nextToCheck;
}
nextToCheck++;
if (nextToCheck === watchedFiles.length) {
nextToCheck = 0;
}
count++;
}
nextFileToCheck = nextToCheck;
}, interval);
}
function addFile(fileName: string, callback: (fileName: string, removed?: boolean) => void): WatchedFile {
const file: WatchedFile = {
fileName,
callback,
mtime: getModifiedTime(fileName)
};
watchedFiles.push(file);
if (watchedFiles.length === 1) {
startWatchTimer();
}
return file;
}
function removeFile(file: WatchedFile) {
watchedFiles = copyListRemovingItem(file, watchedFiles);
}
return {
getModifiedTime: getModifiedTime,
poll: poll,
startWatchTimer: startWatchTimer,
addFile: addFile,
removeFile: removeFile
};
}
// REVIEW: for now this implementation uses polling.
// The advantage of polling is that it works reliably
// on all os and with network mounted files.
// For 90 referenced files, the average time to detect
// changes is 2*msInterval (by default 5 seconds).
// The overhead of this is .04 percent (1/2500) with
// average pause of < 1 millisecond (and max
// pause less than 1.5 milliseconds); question is
// do we anticipate reference sets in the 100s and
// do we care about waiting 10-20 seconds to detect
// changes for large reference sets? If so, do we want
// to increase the chunk size or decrease the interval
// time dynamically to match the large reference set?
const watchedFileSet = createWatchedFileSet();
function isNode4OrLater(): Boolean {
//.........这里部分代码省略.........
示例9: getModifiedTime
function getModifiedTime(fileName: string): Date {
return _fs.statSync(fileName).mtime;
}
示例10: return
return (host: Tree, context: FileSystemSchematicContext) => {
const workspace = getWorkspace(host);
const project = getProjectFromWorkspace(workspace, options.project);
const defaultComponentOptions = getDefaultComponentOptions(project);
// TODO(devversion): Remove if we drop support for older CLI versions.
// This handles an unreported breaking change from the @angular-devkit/schematics. Previously
// the description path resolved to the factory file, but starting from 6.2.0, it resolves
// to the factory directory.
const schematicPath = statSync(context.schematic.description.path).isDirectory() ?
context.schematic.description.path :
dirname(context.schematic.description.path);
const schematicFilesUrl = './files';
const schematicFilesPath = resolve(schematicPath, schematicFilesUrl);
// Add the default component option values to the options if an option is not explicitly
// specified but a default component option is available.
Object.keys(options)
.filter(optionName => options[optionName] == null && defaultComponentOptions[optionName])
.forEach(optionName => options[optionName] = defaultComponentOptions[optionName]);
if (options.path === undefined) {
// TODO(jelbourn): figure out if the need for this `as any` is a bug due to two different
// incompatible `WorkspaceProject` classes in @angular-devkit
options.path = buildDefaultPath(project as any);
}
options.module = findModuleFromOptions(host, options);
const parsedPath = parseName(options.path!, options.name);
options.name = parsedPath.name;
options.path = parsedPath.path;
options.selector = options.selector || buildSelector(options, project.prefix);
validateName(options.name);
validateHtmlSelector(options.selector!);
// In case the specified style extension is not part of the supported CSS supersets,
// we generate the stylesheets with the "css" extension. This ensures that we don't
// accidentally generate invalid stylesheets (e.g. drag-drop-comp.styl) which will
// break the Angular CLI project. See: https://github.com/angular/material2/issues/15164
if (!supportedCssExtensions.includes(options.style!)) {
// TODO: Cast is necessary as we can't use the Style enum which has been introduced
// within CLI v7.3.0-rc.0. This would break the schematic for older CLI versions.
options.style = 'css' as Style;
}
// Object that will be used as context for the EJS templates.
const baseTemplateContext = {
...strings,
'if-flat': (s: string) => options.flat ? '' : s,
...options,
};
// Key-value object that includes the specified additional files with their loaded content.
// The resolved contents can be used inside EJS templates.
const resolvedFiles = {};
for (let key in additionalFiles) {
if (additionalFiles[key]) {
const fileContent = readFileSync(join(schematicFilesPath, additionalFiles[key]), 'utf-8');
// Interpolate the additional files with the base EJS template context.
resolvedFiles[key] = interpolateTemplate(fileContent)(baseTemplateContext);
}
}
const templateSource = apply(url(schematicFilesUrl), [
options.skipTests ? filter(path => !path.endsWith('.spec.ts')) : noop(),
options.inlineStyle ? filter(path => !path.endsWith('.__style__')) : noop(),
options.inlineTemplate ? filter(path => !path.endsWith('.html')) : noop(),
// Treat the template options as any, because the type definition for the template options
// is made unnecessarily explicit. Every type of object can be used in the EJS template.
template({indentTextContent, resolvedFiles, ...baseTemplateContext} as any),
// TODO(devversion): figure out why we cannot just remove the first parameter
// See for example: angular-cli#schematics/angular/component/index.ts#L160
move(null as any, parsedPath.path),
]);
return chain([
branchAndMerge(chain([
addDeclarationToNgModule(options),
mergeWith(templateSource),
])),
])(host, context);
};
示例11: getNodeSystem
//.........这里部分代码省略.........
// If a BOM is required, emit one
if (writeByteOrderMark) {
data = "\uFEFF" + data;
}
let fd: number;
try {
fd = _fs.openSync(fileName, "w");
_fs.writeSync(fd, data, undefined, "utf8");
}
finally {
if (fd !== undefined) {
_fs.closeSync(fd);
}
}
}
function getAccessibleFileSystemEntries(path: string): FileSystemEntries {
try {
const entries = _fs.readdirSync(path || ".").sort();
const files: string[] = [];
const directories: string[] = [];
for (const entry of entries) {
// This is necessary because on some file system node fails to exclude
// "." and "..". See https://github.com/nodejs/node/issues/4002
if (entry === "." || entry === "..") {
continue;
}
const name = combinePaths(path, entry);
let stat: any;
try {
stat = _fs.statSync(name);
}
catch (e) {
continue;
}
if (stat.isFile()) {
files.push(entry);
}
else if (stat.isDirectory()) {
directories.push(entry);
}
}
return { files, directories };
}
catch (e) {
return { files: [], directories: [] };
}
}
function readDirectory(path: string, extensions?: string[], excludes?: string[], includes?: string[]): string[] {
return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries);
}
const enum FileSystemEntryKind {
File,
Directory
}
function fileSystemEntryExists(path: string, entryKind: FileSystemEntryKind): boolean {
try {
const stat = _fs.statSync(path);
switch (entryKind) {
示例12: onlyDirectory
function onlyDirectory(file: string) {
return statSync(file).isDirectory()
&& config.dirsToSkip.indexOf(file) < 0;
}
示例13:
.filter(componentName => (statSync(path.join(componentsDir, componentName))).isDirectory());
示例14: run
// a dirty wrapper to allow async functionality in the setup
async function run(): Promise<any> {
const source = getCISource(process.env, app.externalCiProvider || undefined)
if (!source) {
console.log("Could not find a CI source for this run. Does Danger support this CI service?")
console.log(`Danger supports: ${sentence(providers.map(p => p.name))}.`)
if (!process.env["CI"]) {
console.log("You may want to consider using `danger pr` to run Danger locally.")
}
process.exitCode = 1
}
// run the sources setup function, if it exists
if (source && source.setup) {
await source.setup()
}
if (source && !source.isPR) {
// This does not set a failing exit code
console.log("Skipping Danger due to not this run not executing on a PR.")
}
if (source && source.isPR) {
const platform = getPlatformForEnv(process.env, source)
if (!platform) {
console.log(chalk.red(`Could not find a source code hosting platform for ${source.name}.`))
console.log(
`Currently DangerJS only supports GitHub, if you want other platforms, consider the Ruby version or help out.`
)
process.exitCode = 1
}
if (platform) {
console.log(`${chalk.bold("OK")}, everything looks good: ${source.name} on ${platform.name}`)
const dangerFile = dangerfilePath(program)
try {
const stat = fs.statSync(dangerFile)
if (!!stat && stat.isFile()) {
d(`executing dangerfile at ${dangerFile}`)
const config = {
stdoutOnly: app.textOnly,
verbose: app.verbose,
}
const exec = new Executor(source, platform, config)
exec.setupAndRunDanger(dangerFile)
} else {
console.error(chalk.red(`Looks like your path '${dangerFile}' is not a valid path for a Dangerfile.`))
process.exitCode = 1
}
} catch (error) {
process.exitCode = 1
console.error(error.message)
console.error(error)
}
}
}
}
示例15:
.filter(sp => !fs.statSync(path.join(p, sp)).isDirectory());