0

I have an Event Hub Triggered TypeScript Azure Function. I am trying to write the events receive to a local file when executing with Azure Function Core Tools. This is just to help with development, and not something I will be doing in production or inside of Azure itself.

import { AzureFunction, Context } from "@azure/functions"
import fs = require('fs');

const eventHubTrigger: AzureFunction = async function (context: Context, eventHubMessages: any[]): Promise<void> {
    context.log(`Eventhub trigger function called for message array ${eventHubMessages}`);

    eventHubMessages.forEach((message, index) => {
        context.log(`Processed message ${message}`);

        let data = JSON.stringify(message, null, 2);
        fs.writeFile('messages.json', data, { flag: 'a+' }, (err) => {
            if (err) throw err;
            context.log('Data written to file');
        });

    });
};

export default eventHubTrigger;

When I run this function with the Azure Function Core Tools, there is no 'messages.json' file in the project root (or anywhere I can find). Please advice on how I can write this JSON data to local disk when executing with Azure Function Core Tools.

Andrew
  • 902
  • 1
  • 11
  • 28

1 Answers1

0

The problem here is that fs.writeFile is an asynchronous operation but the function doesn't wait for it since the function is made async without any await.

Here is one way you can fix it by not using async and calling context.done() instead

import { AzureFunction, Context } from "@azure/functions"
import fs = require('fs');

const eventHubTrigger: AzureFunction = function (context: Context, eventHubMessages: any[]): Promise<void> {
  context.log(`Eventhub trigger function called for message array ${eventHubMessages}`);

  let dataToWrite = "";
  eventHubMessages.forEach((message, index) => {
    context.log(`Processed message ${message}`);

    let data = JSON.stringify(message, null, 2);
    dataToWrite += data;
  });

  fs.writeFile('messages.json', dataToWrite, { flag: 'a+' }, (err) => {
    if (err) throw err;
    context.log('Data written to file');
    context.done();
  });
};

export default eventHubTrigger;

Another way would be to promisify the fs methods as covered in this SO thread.

PramodValavala
  • 6,026
  • 1
  • 11
  • 30