Skip to content

Commit

Permalink
fs/co: add fs.exists and wait for promise on co.clearInterval.
Browse files Browse the repository at this point in the history
  • Loading branch information
chjj committed Oct 18, 2017
1 parent aeb3d8f commit 1c1e429
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
18 changes: 17 additions & 1 deletion lib/utils/co.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,18 +208,24 @@ async function every(jobs) {
function startInterval(func, time, self) {
const ctx = {
timer: null,
stopped: false
stopped: false,
running: false,
resolve: null
};

const cb = async () => {
assert(ctx.timer != null);
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();
}
};

Expand All @@ -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();
}

/**
Expand Down
22 changes: 20 additions & 2 deletions lib/utils/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 1c1e429

Please sign in to comment.