I am looking to read files in a folder using Node.js. The incoming files are text files, with a given name (for example, 'FishText1')
The folder will be having new files added to it constantly, and each of these new file will ALWAYS be called 'FishText' + int.
Currently, I am just using this to perform a task on the text file, in this case moving it to another folder (later in my project I will be looking to perform searches through these text files for certain strings, but will get to that later and have a plan for that), and at the moment have some code which does this perfectly, see below. [NB this was taken from code suggested on another thread, by user 'adotout', 30th July 2013]
My question is, is there a better way than using a forced 'while' loop, which will stop when the processed.js file gets to the end of its list - ie when a new text file is added, I want them to be processed too, without having to rerun processed.js.
Extra Info: I am aware that this isn't the most elegant way to do this, so any help in streamlining it would also be appreciated, as this is working up to be part of a bigger project. The files themselves are always going to be <1kb, however, could be several thousand per hour which need to be processed. The requirement is that they are processed 'live' rather than waiting until they have finished and then processing them all.
var fileExist = true;
var fileNumber = 1;
while (fileExist) {
** Not my actual code **
** Work PC is at work and I dont have a local copy **
if __DIR/FishText + fileNumber + .txt
Write __NewDIR/NewText + fileNumber + .xml
fileNumber++
else
error message to console
}
Current results are as expected - I can move all of the files to my new destination folder, but if a new file is added AFTER I run the 'processor.js', then I have to run it again.
So, I have given the 'Chokidar' approach a try, and I cant seem to get any of the code to run - not even within Atom (which I am using to write my code). See full code below, with directories omitted.
When I run the code 'processor.js' the command line just jumps to a new line, as if it has run the process, but I see no output from my code, I would expect to see something, as I have purposefully includes a line which prints out the file to console.
var processedFileNumber = 1;
var chokidar = require('chokidar')
var watcher = chokidar.watch('__DIR', {ignored: /^\./, persistant: true})
watcher
.on('add', function(path) {
const file = readFile ('__DIR/file ' + processedFileNumber + '.txt', 'utf8');
console.log("Print something");
writeFile('__DIR/fileXML ' + processedFileNumber + '.xml', data);
processedFileNumber++;
})
.on('error', function(error) {
console.error('Error Happened', error)
})