CodingLittle
CodingLittle

Reputation: 1857

How to read file from @google-cloud/storage?

I am retriving a file from my bucket.

I get the file and want to read it's contents but I do not want to download it to my local project i just want to read the contents, take the data and do other operations with it.

my code:

export const fileManager = async () => {
  try {
    const source = 'upload/';

    const options = { prefix: source, delimiter: '/' };

    const remoteFile = st.bucket(bName).file('myData.csv');

    const readFileData;

    remoteFile
      .createReadStream()
      .on('error', err => {
        console.log('error');
      })
      .on('response', response => {
        readFileData = response;
        console.log('success');
        // Server connected and responded with the specified status and headers.
      })
      .on('end', () => {
        console.log('end');
        // The file is fully downloaded.
      });

console.log("data", readFileData)

  } catch (error) {
    console.log('Error Is', error);
  }
};

readFileData is undefined.

Is this possible? Every example I find envolves me downloading the file.

Upvotes: 2

Views: 4330

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317352

createReadStream is asynchronous and returns immediately. You have to use the callbacks to find out when the download to memory is complete. Right now, your code is always going to print "data undefined" because it's trying to print the response before it's available.

createReadStream is definitely the right way to go, but you will have to understand how node streams work in order to process the results correctly. There is a whole section in the linked documentation for reading streams, which is what you want to do here. The way you deal with the stream is not specific to Cloud Storage - it's the same for all node streams.

You might be helped by the answers to these questions that deal with reading node streams:

Upvotes: 2

Related Questions