fs/co: add fs.exists and wait for promise on co.clearInterval.

This commit is contained in:
Christopher Jeffrey 2017-10-15 02:17:01 -07:00
parent aeb3d8f352
commit 1c1e429383
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
2 changed files with 37 additions and 3 deletions

View File

@ -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();
}
/**

View File

@ -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);