Created
April 11, 2023 13:50
-
-
Save keepitsimple/ff7391266d819732d7bc7986a1ae11d6 to your computer and use it in GitHub Desktop.
Пример буфера на получение данных и сохранением из него с debounce
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
/* | |
каждые 250 мс нам поступает асинхронно новая запись которая дописывается во входящий буфер | |
процедура записи извлекает элементы с начала буфера и записывает в лог файл. | |
процедура записи обернута в debounce | |
если данные не поступают 500 мс или более то происходит запись данных в лог файл | |
также принудительно после 1000 мс так же происходит запись в лог файл | |
npm install | |
node index.js | |
*/ | |
const fs = require('node:fs'); | |
const debounce = require('lodash.debounce') | |
const inputBuffer = [] | |
const fd = fs.openSync('db.txt', 'w') | |
let i = 1; | |
function storeData() { | |
// фиксируем кол-во элементов в буфере на текущий момент; помним что в буфер асинхронно дописываются новые данные | |
const len = inputBuffer.length | |
if (len === 0) return | |
const buffer = inputBuffer.splice(0, len) | |
const str = buffer.reduce((prev, current) => { | |
return prev.concat(JSON.stringify(current)) | |
}, '') | |
fs.writeSync(fd, str + '\n---\n') | |
} | |
const debouncedStoreData = debounce(() => { | |
process.stdout.write(`|`) | |
storeData() | |
}, 500, {maxWait: 1000}) // maxWait запускает запись данных даже если новые данные продолжают поступать | |
function myLoop(n) { | |
setTimeout(() => { | |
process.stdout.write(`.`); | |
// получаем данные и кладем в буфер | |
inputBuffer.push({id: i, name: `record ${i}`, timestamp: Date.now()}) | |
// сохраняем данные | |
debouncedStoreData() | |
if (++i <= n) { | |
myLoop(n); | |
return | |
} | |
setTimeout(() => { | |
if (fd !== null) fs.closeSync(fd) | |
}, 1000) | |
}, 250) | |
} | |
console.log('Справка: получение данных - ".", запись даных в файл - "|", лог пишется в файл db.txt ') | |
myLoop(40); |
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
{ | |
"name": "debounce", | |
"version": "1.0.0", | |
"description": "Node debounce", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"lodash.debounce": "^4.0.8" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment