Home > database >  Node.JS, How do i make the code await a pipe to finish creating a file?
Node.JS, How do i make the code await a pipe to finish creating a file?

Time:11-17

I have the following code:

const fs = require('fs');
var get = require('get-file');

async function func1(){
  get('jonschlinkert/get-file', 'package.json', function(err, res) {
    if (err) return console.error(err);   
    var file = fs.createWriteStream('mani.json'); 
    res.pipe(file);
  });
};

async function func2(){
  await func1();
  fs.readFile("./mani.json", "utf8", (err, jsonString) => {
    if (err) {
      console.log("Error reading file from disk:", err);
      return;
    }
    try {
      const test = JSON.parse(jsonString);      
      console.log(test.files['main.js']);
    } catch (err) {
      console.log("Error parsing JSON string:", err);
    }
  });
};
func2();

I need to find a way to make function 2 only activate after the pipe from function 1 finished creating the file, i tough using await func1(); would do the trick but did nothing so function 2 tries to read a file that is non existent.

Thank you in advance, have a nice day.

CodePudding user response:

Ok, after studying the documentation found that when a stream is done it sets its flag .finish. So all i need to do is set an "event listener"* to .finish and inside it call func2, don't even need the async I was trying to use and failed on making it work:

const fs = require('fs');
var get = require('get-file');

function func1(){
  get('jonschlinkert/get-file', 'package.json', function(err, res) {
    if (err) return console.error(err);   
    var file = fs.createWriteStream('mani.json');

    file.on('finish', () => {      
      func2();
    });

    res.pipe(file);
  });
};

function func2(){
  fs.readFile("./mani.json", "utf8", (err, jsonString) => {
    if (err) {
      console.log("Error reading file from disk:", err);
      return;
    }
    try {
      const test = JSON.parse(jsonString);      
      console.log(test.files['main.js']);
    } catch (err) {
      console.log("Error parsing JSON string:", err);
    }
  });
};
func1();

Thank you everyone, hope this helps someone one day.

*I'm not sure if it is called an event listener.

  • Related