From 1c1e429383ddecf77d6b47f3606a0f7e63c144b9 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Sun, 15 Oct 2017 02:17:01 -0700 Subject: [PATCH] fs/co: add fs.exists and wait for promise on co.clearInterval. --- lib/utils/co.js | 18 +++++++++++++++++- lib/utils/fs.js | 22 ++++++++++++++++++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/lib/utils/co.js b/lib/utils/co.js index 20b24e1d8..7fb6fff7d 100644 --- a/lib/utils/co.js +++ b/lib/utils/co.js @@ -208,7 +208,9 @@ async function every(jobs) { function startInterval(func, time, self) { const ctx = { timer: null, - stopped: false + stopped: false, + running: false, + resolve: null }; const cb = async () => { @@ -216,10 +218,14 @@ function startInterval(func, time, self) { ctx.timer = null; try { + ctx.running = true; await func.call(self); } finally { + ctx.running = false; if (!ctx.stopped) ctx.timer = setTimeout(cb, time); + else if (ctx.resolve) + ctx.resolve(); } }; @@ -235,11 +241,21 @@ function startInterval(func, time, self) { function stopInterval(ctx) { assert(ctx); + if (ctx.timer != null) { clearTimeout(ctx.timer); ctx.timer = null; } + ctx.stopped = true; + + if (ctx.running) { + return new Promise((r) => { + ctx.resolve = r; + }); + } + + return Promise.resolve(); } /** diff --git a/lib/utils/fs.js b/lib/utils/fs.js index 28f710675..5c1a7be96 100644 --- a/lib/utils/fs.js +++ b/lib/utils/fs.js @@ -22,8 +22,26 @@ exports.closeSync = fs.closeSync; exports.constants = fs.constants; exports.createReadStream = fs.createReadStream; exports.createWriteStream = fs.createWriteStream; -exports.exists = co.promisify(fs.exists); -exports.existsSync = fs.existsSync; +exports.exists = async (file) => { + try { + await exports.stat(file); + return true; + } catch (e) { + if (e.code === 'ENOENT') + return false; + throw e; + } +}; +exports.existsSync = (file) => { + try { + exports.statSync(file); + return true; + } catch (e) { + if (e.code === 'ENOENT') + return false; + throw e; + } +}; exports.fchmod = co.promisify(fs.fchmod); exports.fchmodSync = fs.fchmodSync; exports.fchown = co.promisify(fs.fchown);