From a9cbea42595d76236bedd9613702b07e78d65a04 Mon Sep 17 00:00:00 2001 From: Andrew Casey Date: Wed, 15 Jan 2020 12:53:40 -0800 Subject: [PATCH] Use fs.existsSync to check for cancellation (#36190) Unlike statSync, it doesn't throw if the file doesn't exist, saving both time and allocations. --- src/cancellationToken/cancellationToken.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/cancellationToken/cancellationToken.ts b/src/cancellationToken/cancellationToken.ts index 059ef37c8f1..aaa19750b87 100644 --- a/src/cancellationToken/cancellationToken.ts +++ b/src/cancellationToken/cancellationToken.ts @@ -9,13 +9,14 @@ interface ServerCancellationToken { } function pipeExists(name: string): boolean { - try { - fs.statSync(name); - return true; - } - catch (e) { - return false; - } + // Unlike statSync, existsSync doesn't throw an exception if the target doesn't exist. + // A comment in the node code suggests they're stuck with that decision for back compat + // (https://github.com/nodejs/node/blob/9da241b600182a9ff400f6efc24f11a6303c27f7/lib/fs.js#L222). + // Caveat: If a named pipe does exist, the first call to existsSync will return true, as for + // statSync. Subsequent calls will return false, whereas statSync would throw an exception + // indicating that the pipe was busy. The difference is immaterial, since our statSync + // implementation returned false from its catch block. + return fs.existsSync(name); } function createCancellationToken(args: string[]): ServerCancellationToken {