Updated on 2024-05-28 GMT+08:00

Node.js

Prerequisites

  • You have a Huawei Cloud account and have completed real-name authentication.
  • Your Huawei Cloud account is not in arrears and has sufficient balance for the resources involved in this example.

Procedure

  1. Create a function.

    1. Log in to the FunctionGraph console, choose Functions > Function List in the navigation pane, and click Create Function.
    2. Select Create from scratch, set the function information, and click Create Function.
      • Function Type: Select Event Function.
      • Region: Select AP-Singapore.
      • Function Name: Enter upload-file-1.
      • Agency: Select Use no agency.
      • Runtime: Select Node.js 14.18.
    3. On the Code tab of the function details page, copy the following code to replace the default code, and click Deploy.
      const stream = require("stream");
      const Busboy = require("busboy");
      
      exports.handler = async (event, context) => {
          const logger = context.getLogger()
          logger.info("Function start run.");
          if (!("content-type" in event.headers) ||
              !event.headers["content-type"].includes("multipart/form-data")) {
              return {
                  'statusCode': 200,
                  'headers': {
                      'Content-Type': 'application/json'
                  },
                  'body': 'The request is not in multipart/form-data format.',
              };
          }
      
          const busboy = Busboy({ headers: event.headers });
          let buf = Buffer.alloc(0);
          busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
              logger.info('filename:' + JSON.stringify(filename))
              file.on('data', function (data) {
                  logger.info('Obtains ' + data.length + ' bytes of data.')
                  buf = Buffer.concat([buf, data]);
              });
              file.on('end', function () {
                  logger.info('End data reception');
              });
          });
      
          busboy.on('finish', function () {
              // Data is processed here.
              logger.info(buf.toString());
              return {
                  'statusCode': 200,
                  'headers': {
                      'Content-Type': 'application/json'
                  },
                  'body': 'ok',
              };
          });
      
          // The APIG trigger encodes data using Base64 by default. The data is decoded here.
          const body = Buffer.from(event.body, "base64");
          var bodyStream = new stream.PassThrough();
          bodyStream.end(body);
          bodyStream.pipe(busboy);
      }

  2. Configure a dependency.

    1. Make dependency: To parse uploaded files with busboy, generate dependency busboy.zip for Node.js 14.18. If you use another Node.js version, create the corresponding dependency by referring to Creating a Dependency.
    2. Create dependency: In the navigation pane, choose Functions > Dependencies. Then click Create Dependency, configure the dependency information, and click OK.
      • Name: Enter busboy.
      • Code Entry Mode: Select Upload ZIP.
      • Runtime: Select Node.js 14.18.
      • Upload File: Upload the dependency you made.
    3. Add dependency: On the details page of function upload-file-1, click Add at the bottom of the Code tab. On the Select Dependency page, set Type to Private, select the busboy dependency, and click OK.

  3. Create an APIG trigger.

    1. On the details page of function upload-file-1, choose Configuration > Triggers.
    2. Click Create Trigger, and set Trigger Type to API Gateway (APIG) or API Gateway (Dedicated Gateway). In this example, select API Gateway (APIG).
      • API Name: Retain the default name.
      • API Group: If no API group is available, click Create API Group to create one.
      • Environment: Select RELEASE.
      • Security Authentication: In this example, select None for testing. You can select a more secure authentication mode, such as IAM, for your own services.
      • Protocol: Select HTTPS.
      • Timeout (ms): Retain the default value 5000.

  4. Perform E2E testing.

    The curl tool is used as an example (curl -F is mainly used in Linux). You can also use other tools such as Postman. Create a file named app.log with any content on your local host. Example:

    start something
    run
    stop all

    Run the following command:

    curl -iv {APIG trigger URL} -F upload=@/{Local file path}/app.log
    Figure 1 Example

    On the Monitoring tab of the upload-file-1 function details page, view the file content in the logs. If needed, you can modify the code to save data to OBS or LTS or to directly process the data.