I am trying to use file creation and deletion as a method of data transfer (not the best way, I know.) between python and nodejs. The python side of the program works fine, as I am quite familiar with python 3, but I can't get the node.js script to work.
I've tried various methods of detecting when a file is created, mainly with the use of try {} catch {}
, but none of them have worked.
function fufillRequest(data) {
fs.writeFile('Response.txt', data)
}
while(true) {
try {
fs.readFile('Request.txt', function(err,data) {
console.log(data);
});
} catch {
}
}
The program is supposed to see that the file has been created, read it's contents, delete it and then create and write to a response file.
@jfriend00 solution is correct. However, In the above solution. It never cleans the timeout. It may cause an issue. If u need blocking code and better timer handling u can use setInterval.
Sample:
const checkTime = 1000;
var fs = require("fs");
const messageFile = "test.js";
const timerId = setInterval(() => {
const isExists = fs.existsSync(messageFile, 'utf8')
if(isExists) {
// do something here
clearInterval(timerId)
}
}, checkTime)
You can also run your python program. No need to write another script.
const spawn = require("child_process").spawn;
const proc = spawn('python',["./watch.py"]);
proc.stdout.on('data', (data) => console.log(data.toString()))
proc.stderr.on('data', (data) => console.log(data.toString()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With