fs#Stats TypeScript Examples
The following examples show how to use
fs#Stats.
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: finder.ts From devoirs with MIT License | 6 votes |
// noinspection JSMethodCanBeStatic
private isDirectoryExists(path: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
stat(path, (error: NodeJS.ErrnoException, stats: Stats) => {
if (error) {
if (error.code !== 'ENOENT') {
return reject(error);
}
return resolve(false);
}
resolve(stats.isDirectory());
});
});
}
Example #2
Source File: io.ts From DefinitelyTyped-tools with MIT License | 6 votes |
/**
* Work around a bug where directories bundled on Windows do not have executable permission when extracted on Linux.
* https://github.com/npm/node-tar/issues/7#issuecomment-17572926
*/
function addDirectoryExecutablePermission(_: string, stat: Stats): boolean {
if (stat.isDirectory()) {
stat.mode = addExecutePermissionsFromReadPermissions(stat.mode);
}
return true;
}
Example #3
Source File: RTorrent.ts From cross-seed with Apache License 2.0 | 6 votes |
async function createLibTorrentResumeTree(
meta: Metafile,
dataDir: string
): Promise<LibTorrentResume> {
async function getFileResumeData(
file: FileListing
): Promise<LibTorrentResumeFileEntry> {
const filePath = resolve(dataDir, file.path);
const fileStat = await fs
.lstat(filePath)
.catch(() => ({ isFile: () => false } as Stats));
if (!fileStat.isFile() || fileStat.size !== file.length) {
logger.debug({
label: Label.RTORRENT,
message: `File ${filePath} either doesn't exist or is the wrong size.`,
});
return {
completed: 0,
mtime: 0,
priority: 0,
};
}
return {
completed: Math.ceil(file.length / meta.pieceLength),
mtime: Math.trunc(fileStat.mtimeMs / 1000),
priority: 0,
};
}
return {
bitfield: Math.ceil(meta.length / meta.pieceLength),
files: await Promise.all<LibTorrentResumeFileEntry>(
meta.files.map(getFileResumeData)
),
};
}
Example #4
Source File: index.test.ts From airnode with MIT License | 5 votes |
describe('caching utils', () => {
it('initialises the cache - initPath', () => {
const mkdirSpy = jest.spyOn(fs, 'mkdirSync');
mkdirSpy.mockReturnValueOnce('');
const existsSyncSpy = jest.spyOn(fs, 'existsSync');
existsSyncSpy.mockReturnValueOnce(false);
caching.initPath();
expect(existsSyncSpy).toHaveBeenCalledTimes(1);
expect(mkdirSpy).toHaveBeenCalledTimes(1);
expect(mkdirSpy).toHaveBeenCalledWith(CACHE_BASE_PATH);
});
it(`adds a key to the cache if it doesn't exist`, () => {
const writeFileSpy = jest.spyOn(fs, 'writeFileSync');
writeFileSpy.mockImplementationOnce(() => {});
const existsSyncSpy = jest.spyOn(fs, 'existsSync');
existsSyncSpy.mockReset();
existsSyncSpy.mockReturnValueOnce(false);
caching.addKey('testKey', 'some data', true);
expect(existsSyncSpy).toHaveBeenCalledTimes(1);
expect(writeFileSpy).toHaveBeenCalledTimes(1);
expect(writeFileSpy).toHaveBeenCalledWith('/tmp/airnode-cache/testKey', `"some data"`);
});
it(`sweeps the cache - old files`, () => {
const files = ['1', '2', '3', '4', '5'];
const filesStatData = files.map((file) => ({ file, mtimeMs: 1 }));
const readdirSyncSpy = jest.spyOn(fs, 'readdirSync');
readdirSyncSpy.mockReturnValueOnce(files as unknown as Dirent[]);
const statSyncSpy = jest.spyOn(fs, 'statSync');
statSyncSpy.mockImplementation(
(file: PathLike) =>
filesStatData.find((statData) => file.toString().indexOf(statData.file) > -1)! as unknown as Stats
);
const rmSyncSpy = jest.spyOn(fs, 'rmSync');
rmSyncSpy.mockImplementation(() => {});
caching.sweep();
expect(readdirSyncSpy).toHaveBeenCalledTimes(1);
expect(statSyncSpy).toHaveBeenCalledTimes(files.length);
expect(rmSyncSpy).toHaveBeenCalledTimes(files.length);
});
it(`sweeps the cache - no old files present`, () => {
const files = ['1', '2', '3', '4', '5'];
const filesStatData = files.map((file) => ({ file, mtimeMs: Date.now() }));
const readdirSyncSpy = jest.spyOn(fs, 'readdirSync');
readdirSyncSpy.mockReturnValueOnce(files as unknown as Dirent[]);
const statSyncSpy = jest.spyOn(fs, 'statSync');
statSyncSpy.mockImplementation(
(file: PathLike) =>
filesStatData.find((statData) => file.toString().indexOf(statData.file) > -1)! as unknown as Stats
);
const rmSyncSpy = jest.spyOn(fs, 'rmSync');
rmSyncSpy.mockImplementation(() => {});
caching.sweep();
expect(readdirSyncSpy).toHaveBeenCalledTimes(1);
expect(statSyncSpy).toHaveBeenCalledTimes(files.length);
expect(rmSyncSpy).toHaveBeenCalledTimes(0);
});
});
Example #5
Source File: apply-edit-adapter.ts From atom-languageclient with MIT License | 5 votes |
private static async handleResourceOperation(edit: CreateFile | RenameFile | DeleteFile): Promise<void> {
if (DeleteFile.is(edit)) {
const path = Convert.uriToPath(edit.uri)
const stats: boolean | Stats = await fsp.lstat(path).catch(() => false)
const ignoreIfNotExists = edit.options?.ignoreIfNotExists
if (!stats) {
if (ignoreIfNotExists !== false) {
return
}
throw Error(`Target doesn't exist.`)
}
if (stats.isDirectory()) {
if (edit.options?.recursive) {
return new Promise((resolve, reject) => {
rimraf(path, { glob: false }, (err) => {
if (err) {
reject(err)
}
resolve()
})
})
}
return fsp.rmdir(path, { recursive: edit.options?.recursive })
}
return fsp.unlink(path)
}
if (RenameFile.is(edit)) {
const oldPath = Convert.uriToPath(edit.oldUri)
const newPath = Convert.uriToPath(edit.newUri)
const exists = await fsp
.access(newPath)
.then(() => true)
.catch(() => false)
const ignoreIfExists = edit.options?.ignoreIfExists
const overwrite = edit.options?.overwrite
if (exists && ignoreIfExists && !overwrite) {
return
}
if (exists && !ignoreIfExists && !overwrite) {
throw Error(`Target exists.`)
}
return fsp.rename(oldPath, newPath)
}
if (CreateFile.is(edit)) {
const path = Convert.uriToPath(edit.uri)
const exists = await fsp
.access(path)
.then(() => true)
.catch(() => false)
const ignoreIfExists = edit.options?.ignoreIfExists
const overwrite = edit.options?.overwrite
if (exists && ignoreIfExists && !overwrite) {
return
}
return fsp.writeFile(path, "")
}
}
Example #6
Source File: MockStats.ts From elasticsearch-index-migrate with MIT License | 5 votes |
export class MockStats implements Stats {
atime: Date;
atimeMs: number;
birthtime: Date;
birthtimeMs: number;
blksize: number;
blocks: number;
ctime: Date;
ctimeMs: number;
dev: number;
gid: number;
ino: number;
mode: number;
mtime: Date;
mtimeMs: number;
nlink: number;
rdev: number;
size: number;
uid: number;
constructor() {
this.atime = new Date();
this.atimeMs = 0;
this.birthtime = new Date();
this.birthtimeMs = 0;
this.blksize = 0;
this.blocks = 0;
this.ctime = new Date();
this.ctimeMs = 0;
this.dev = 0;
this.gid = 0;
this.ino = 0;
this.mode = 0;
this.mtime = new Date();
this.mtimeMs = 0;
this.nlink = 0;
this.rdev = 0;
this.size = 0;
this.uid = 0;
}
isBlockDevice(): boolean {
return false;
}
isCharacterDevice(): boolean {
return false;
}
isDirectory(): boolean {
return false;
}
isFIFO(): boolean {
return false;
}
isFile(): boolean {
return true;
}
isSocket(): boolean {
return false;
}
isSymbolicLink(): boolean {
return false;
}
}
Example #7
Source File: cache.ts From lage with MIT License | 5 votes |
function remove(entryPath: string, entryStat: Stats) {
if (entryStat.isDirectory()) {
fs.rmdirSync(entryPath, { recursive: true });
} else {
fs.unlinkSync(entryPath);
}
}
Example #8
Source File: pandoc.ts From obsidian-pandoc with MIT License | 4 votes |
pandoc = async (input: PandocInput, output: PandocOutput, extraParams?: string[])
: Promise<{ result: string, command: string, error: string }> => new Promise(async (resolve, reject) => {
const stdin = input.file === 'STDIN';
const stdout = output.file === 'STDOUT';
let pandoc: ChildProcess;
let result = '';
let error = '';
const fileBaseName = (file: string): string => path.basename(file, path.extname(file));
// Construct the Pandoc arguments list
let args: string[] = [];
if (input.format) {
args.push('--from');
args.push(input.format);
}
if (output.format) {
args.push('--to');
args.push(output.format);
}
if (needsStandaloneFlag(output))
args.push('-s');
if (!stdout) {
args.push('-o');
args.push(output.file);
} else {
args.push('-o');
args.push('-');
}
// // Support Unicode in the PDF output if XeLaTeX is installed
if (output.format === 'pdf' && await lookpath('xelatex'))
args.push('--pdf-engine=xelatex');
if (!stdin) {
args.push(input.file);
}
// The metadata title is needed for ePub and standalone HTML formats
// We use a metadata file to avoid being vulnerable to command injection
if (input.metadataFile) args.push('--metadata-file', input.metadataFile);
// Extra parameters
if (extraParams) {
extraParams = extraParams.flatMap(x => x.split(' ')).filter(x => x.length);
args.push(...extraParams);
}
function start () {
// Spawn a Pandoc child process
// Assumes Pandoc is installed and that the arguments are valid
// The arguments aren't sanitised, so be careful!
const env = Object.assign(process.env);
if (input.pdflatex) {
// Workaround for Windows having different PATH delimiters
// to *every other operating system in existence*
// *sigh*
if (process.platform === 'win32')
env.PATH += ";"
else
env.PATH += ":";
env.PATH += path.dirname(input.pdflatex);
}
pandoc = spawn(input.pandoc || 'pandoc', args, { env: process.env });
if (stdin) {
// TODO: strip some unicode characters but not others
// Currently we're stripping footnote back arrows but no
// other characters to avoid localisation issues
const contents = input.contents.replace(/[\u21a9\ufe0e]/g, '');
pandoc.stdin.write(contents);
pandoc.stdin.end();
}
// Handlers
pandoc.stdout.on('data', (data: any) => {
result += data;
});
pandoc.stderr.on('data', (err: any) => {
error += err;
});
pandoc.stdout.on('end', () => {
const value = {
result, error,
command: 'pandoc ' + args.join(' ')
};
if (output.file !== 'STDOUT') {
fs.stat(output.file, (err: NodeJS.ErrnoException | null, stats: fs.Stats) => {
// Call resolve if the file exists, reject otherwise
if (stats && stats.isFile()) {
resolve(value);
} else {
reject(error);
}
});
} else {
// Call resolve iff there is a nonempty result
(result.length ? resolve : reject)(value);
if (result.length) {
resolve(value);
} else {
reject(error);
}
}
});
}
if (input.file === 'STDIN') {
start();
} else {
// Check if the input file exists, and then start
stat(input.file, (err: NodeJS.ErrnoException | null, stats: Stats) => {
if (stats.isFile()) start();
else reject(new Error('Input file does not exist'));
});
}
})