Last active
June 17, 2024 15:03
-
-
Save lac5/a1929b7532d82e2c1edeb82b20929641 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { open, writeFile } from 'fs'; | |
/** | |
* Writes and overwrites a file in a continuous loop. | |
* | |
* Example: | |
* loopWriteFile('./date.txt', function*() { | |
* while (true) { | |
* yield new Date().toISOString(); | |
* } | |
* }).catch(e => { | |
* console.error('Done'); | |
* }); | |
* | |
* @param {(string|Buffer)} filename The path to the file to write to. | |
* @param {()=> Iterator<any>} generator The callback that generates the data to be written. | |
* @param {number} [time = 0] The time between intervals. | |
* @return {Promise<any>} | |
*/ | |
export default function loopWriteFile(filename, generator, time = 0) { | |
return new Promise(function(resolve, reject) { | |
/** @type {number?} */ | |
let timeout = null; | |
let start = Date.now(); | |
open(filename, 'w', function(/** @type {Error?} */ error, file) { | |
let g = generator(); | |
iterate(); | |
function next(/** @type {Error?} */ e) { | |
error = e; | |
let now = Date.now(); | |
timeout = setTimeout(iterate, Math.max(time + start - now, 0)); | |
start = now; | |
} | |
function iterate() { | |
try { | |
let call = error | |
? g.throw(error) | |
: g.next(); | |
if (!call.done) { | |
Promise.resolve(call.value).then(function(value) { | |
writeFile(file, value == null ? '' : value, function(e) { | |
if (e) { | |
next(e); | |
} else { | |
let d = new Date(); | |
fs.utimes(filename, d, d, next); | |
} | |
}); | |
}).catch(next); | |
} else { | |
resolve(call.value); | |
} | |
} catch (e) { | |
reject(e); | |
} | |
} | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment