Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until file is created to read it in node.js

Tags:

node.js

fs

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.

like image 576
Anaxion Avatar asked Sep 12 '25 10:09

Anaxion


1 Answers

@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()))
like image 149
xdeepakv Avatar answered Sep 14 '25 02:09

xdeepakv