Skip to content

Instantly share code, notes, and snippets.

@lac5
Last active June 17, 2024 15:03
Show Gist options
  • Save lac5/a1929b7532d82e2c1edeb82b20929641 to your computer and use it in GitHub Desktop.
Save lac5/a1929b7532d82e2c1edeb82b20929641 to your computer and use it in GitHub Desktop.
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