How to asynchronously write and read from the same file in node?

I have data coming through websocket. It sends binary data in 20,000 chunks. I need to combine each of these fragments so that the backend process can read data as a continuous stream as it arrives.

//Create the file and append binary as it comes in

    tmp.file({postfix: '.raw' },function (err, path, fd, cleanup) {
    if (err) throw err;
    newPath = path
        fs.appendFile(newPath, new Buffer(binary), (err) => {
            if (err) throw err;

        })
    })

//Read the file as it is written
    fs.createReadStream(newPath).pipe(recStream);

At the moment, I have a simple half second delay on createReadStreamto make sure that there is data in the file.

This, of course, does not seem correct and does not work. What is the right way to do this?

+4
source share
1 answer

, , , (drain). , :

. write(chunk) false, , ; , . (chunk , false , - false , , , , highWaterMark.)

(A) . , drain.

drain s:

  • . A B, .
  • A . , pipe(), , , , . (, pipe() , end().)
  • temp A end, A. 1 B. ( B , , .)

, , , write(null) , , . !

, . , .

, , , . , , , , , . - prod?

+2

Source: https://habr.com/ru/post/1671731/


All Articles