-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
44 lines (39 loc) · 1.28 KB
/
index.js
File metadata and controls
44 lines (39 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const fs = require('fs');
const path = require('path');
const chokidar = require('chokidar'); // you need to install it first
let textFiles = {};
const dirPath = '/path/to/your/directory';
// Initial load
fs.readdir(dirPath, (err, files) => {
if (err) {
console.error(`Error reading directory: ${err}`);
return;
}
// Filter for '.txt' files
files = files.filter(file => path.extname(file).toLowerCase() === '.txt');
files.forEach(file => {
fs.readFile(path.join(dirPath, file), 'utf8', (err, data) => {
if (err) {
console.error(`Error reading file: ${err}`);
return;
}
// add each file content to textFiles object
textFiles[file] = data;
});
});
});
// File watcher
chokidar.watch(dirPath).on('change', (filePath) => {
if(path.extname(filePath).toLowerCase() === '.txt') {
const file = path.basename(filePath);
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error(`Error reading file: ${err}`);
return;
}
// update file content in textFiles object
textFiles[file] = data;
console.log(`Updated content of ${file}`);
});
}
});