Tüm Ürünler
Search
Belge Merkezi

Function Compute:İşleyici

Son Güncelleme:Oct 08, 2026

Olaylara yanıt vermek ve iş mantığınızı yürütmek için bir Node.js işleyici kullanabilirsiniz. Bu konu, Node.js işleyicilerin kavramını ve yapısını açıklar ve örnekler sunar.

İşleyici nedir?

Bir FC işlevi için işleyici, istekleri işleyen işlev kodunuzdaki yöntemdir. FC işleviniz çağrıldığında, Function Compute yapılandırılmış işleyiciyi çalıştırarak isteği işler. Function Compute konsolu içindeki Handler parametresini kullanarak işleyiciyi yapılandırabilirsiniz.

Node.js FC işlevi için işleyici biçimi filename.methodName şeklindedir. Örneğin, dosyanızın adı index.js veya index.mjs ise ve yöntemin adı handler ise işleyici index.handler olur.

FC işlevleri ve ilgili işlemler hakkında daha fazla bilgi için bkz. Olay tetiklemeli işlev oluşturma.

İşleyici yapılandırmaları Function Compute yapılandırma özelliklerine uygun olmalıdır. Yapılandırma özellikleri işleyici türüne göre değişir.

İşleyici imzası

Not

Function Compute Node.js 18 çalışma zamanından itibaren ECMAScript (ES) modüllerini destekler. Daha önceki sürümlerde (Node.js 16 ve öncesi) Function Compute yalnızca CommonJS modüllerini destekliyordu. Daha fazla bilgi için bkz. İşleyiciyi ES modülü olarak belirtme.

Basit bir olay işleyicisi aşağıdaki imzaya sahiptir:

Node.js 18 veya Node.js 20

ES modülü

Not

Bu örnek kod tek tıkla dağıtımı destekler. Kodu doğrudan Function Compute (FC) içinde dağıtabilirsiniz.start-fc3-nodejs-es

// index.mjs
export const handler = async (event, context) => {
  console.log("receive event: \n" + event);
  return "Hello World!";
};

CommonJS modülü

// index.js
exports.handler = async function(event, context) {
  console.log("receive event: \n" + event);
  return "Hello World!";
};

Node.js 16 ve önceki sürümler

// index.js
exports.handler = async function(event, context, callback) {
  console.log("event: \n" + event);
  callback(null, 'hello world');
};

Yukarıdaki örnek kodun açıklaması şu şekildedir:

handler yöntemin adıdır ve Function Compute konsolu içinde yapılandırılan Handler öğesine karşılık gelir. Örneğin, bir işlev oluştururken Handler olarak index.handler belirtirseniz Function Compute index.js dosyasında tanımlanan handler işlevini yükler ve yürütmeyi başlatır.

Function Compute çalışma zamanı, istek parametrelerini istek işleyicisine iletir. İlk parametre, istek yükünü içeren event nesnesidir. event nesnesi Buffer türündedir ve bunu ihtiyacınız olan nesne türüne dönüştürebilirsiniz. İkinci parametre, çağrı için çalışma zamanı bağlam bilgileri sağlayan context nesnesidir. Daha fazla bilgi için bkz. Bağlam.

    Not
    • Node.js 18 veya sonraki bir çalışma zamanı kullanırken callback yerine Async/Await özelliğini kullanın.

    • Function Compute döndürülen sonucu türüne göre dönüştürür.

      • Buffer türü: Olduğu gibi döndürülür.

      • Object türü: JSON biçimine dönüştürülerek döndürülür.

      • Diğer türler: Dizeye dönüştürülerek döndürülür.

Async/Await

Node.js 18 veya sonraki bir çalışma zamanı ortamı kullanırken Async/Await yaklaşımını kullanmanızı öneririz. Async/Await, Node.js'de asenkron kod yazmak için iç içe geçmiş geri aramalar veya zincirleme çağrılardan kaçınan özlü ve okunabilir bir yoldur.

Önemli

Node.js 16 çalışma zamanını veya önceki sürümleri kullanıyorsanız yanıt göndermek için callback yöntemini açıkça kullanmanız gerekir. Aksi takdirde istek zaman aşımına uğrar.

Async/Await yaklaşımının geri arama işlevlerine callback kıyasla aşağıdaki avantajları vardır:

  • Geliştirilmiş okunabilirlik: async/await kullanan kod daha doğrusal ve senkronizedir. Bu durum kodun anlaşılmasını ve bakımını kolaylaştırır. Derin iç içe geçmiş geri aramalardan kaçınarak daha net bir kod yapısı sağlar.

  • Daha basit hata ayıklama ve hata işleme: Asenkron işlemlerde hataları daha kolay yakalamak ve işlemek için try-catch bloklarını kullanabilirsiniz. Hata yığını daha nettir ve bu sayede hatanın kaynağını daha doğru şekilde izleyebilirsiniz.

  • Daha yüksek verimlilik: Geri aramalar genellikle kodun farklı bölümleri arasında geçiş yapılmasını gerektirir. async/await yaklaşımı bağlam değiştirme sayısını azaltarak kod verimliliğini artırır.

Örnek 1: JSON biçimli parametreleri ayrıştırma

Örnek kod

Function Compute JSON biçimli parametreleri doğrudan işlevinize iletir. Bu parametreleri kodunuzda ayrıştırmanız gerekir. Aşağıdaki kod, JSON biçimli bir olayın nasıl ayrıştırılacağını gösterir.

ES modülü

Not

Bu örnek yalnızca Node.js 18 ve sonraki çalışma zamanlarında desteklenir.

export const handler = async (event, context) => {
  var eventObj = JSON.parse(event.toString());
  return eventObj['key'];
};

CommonJS modülü

Not

Bu örnek kod tek tıkla dağıtımı destekler. Bu kodu Function Compute (FC) içine tek tıkla dağıtabilirsiniz.start-fc3-nodejs-json

exports.handler = function(event, context, callback) {
  var eventObj = JSON.parse(event.toString());
  callback(null, eventObj['key']);
};

Ön koşullar

Bir Node.js işlevi oluşturun. Daha fazla bilgi için bkz. Olay tetiklemeli işlev oluşturma. Kodunuzu bir ES modülü olarak belirtmek istiyorsanız işlevi oluştururken çalışma zamanı olarak Node.js 18 veya Node.js 20'yi seçin.

Yordam

  1. Log on to the Function Compute console. In the navigation pane on the left, choose Function Management > Functions.

  2. In the top navigation bar, select a region. On the Functions page, click the target function.

  3. On the function configuration page, select the Code tab. In the code editor, enter the preceding sample code and then click Deploy.

    Not

    The handler for the function in the preceding sample code is the handler method in index.js. If your function's handler is configured differently, update the corresponding file and method.

  4. On the Code tab, click the image.png icon to the right of Test Function. From the drop-down list, select Configure Test Parameters. Enter the following sample test parameters and then click OK.

    {
      "key": "value"
    }
  5. Click Test Function.

    After the function runs successfully, check the response. The response is value.

Örnek 2: Geçici AccessKey çifti kullanarak OSS kaynaklarını güvenli bir şekilde okuma ve yazma

Örnek kod

Use the temporary AccessKey pair that Function Compute provides to access Object Storage Service (OSS). The following code is an example.

ES modülü

Not

This example runs only in Node.js 18 or later runtimes.

// index.mjs
import OSSClient from 'ali-oss';

export const handler = async (event, context) => {
    console.log(event.toString());

    var ossClient = new OSSClient({
        accessKeyId: context.credentials.accessKeyId,
        accessKeySecret: context.credentials.accessKeySecret,
        stsToken: context.credentials.securityToken,
        region: 'oss-cn-shenzhen',
        bucket: 'my-bucket',
    });

    try {
      const uploadResult = await ossClient.put('myObj', Buffer.from('hello, fc', "utf-8"));
      console.log('upload success, ', uploadResult);
      return "put object"
    } catch (error) {
      throw error
    }
};

Code description:

  • context.credentials: Obtains the temporary AccessKey pair from the context parameter. This avoids hardcoding sensitive information such as passwords in the code.

  • myObj: The name of the OSS object.

  • Buffer.from('hello, fc', "utf-8"): The content of the object to upload.

  • return "put object": If the upload is successful, put object is returned.

  • throw err: If the upload fails, an exception is thrown.

CommonJS modülü

Not

This sample code supports one-click deployment. Deploy this code to Function Compute (FC) with a single click.start-fc3-nodejs-oss

var OSSClient = require('ali-oss');

exports.handler = function (event, context, callback) {
    console.log(event.toString());

    var ossClient = new OSSClient({
        accessKeyId: context.credentials.accessKeyId,
        accessKeySecret: context.credentials.accessKeySecret,
        stsToken: context.credentials.securityToken,
        region: `oss-${context.region}`,
    		bucket: process.env.BUCKET_NAME,
    });

    ossClient.put('myObj', Buffer.from('hello, fc', "utf-8")).then(function (res) {
        callback(null, 'put object');
    }).catch(function (err) {
        callback(err);
    });  
};

Code description:

  • context.credentials: Obtains the temporary AccessKey pair from the context parameter. This avoids hardcoding sensitive information such as passwords in the code.

  • myObj: The name of the OSS object.

  • Buffer.from('hello, fc', "utf-8"): The content of the object to upload.

  • callback(null, 'put object'): If the upload is successful, put object is returned.

  • callback(err): If the upload fails, err is returned.

Ön koşullar

Yordam

  1. Log on to the Function Compute console. In the navigation pane on the left, choose Function Management > Functions.

  2. In the top navigation bar, select a region. On the Functions page, click the target function.

  3. (Optional) On the Function Details tab of the function, click the Code tab. In the WebIDE section, choose to open a terminal. Then, run the following command to install the ali-oss dependency.

    npm install ali-oss --save

    After the installation is complete, the node_modules folder is generated in the code directory on the left side of the WebIDE. The folder contains the ali-oss directory and other dependency libraries.

  4. On the Function Details tab of the function, click the Code tab. In the code editor, enter the sample code provided above. Then, save the code and click Deploy.

    Not
    • In the sample code, the handler of the function is the handler method in the index.js or index.mjs file. If your function uses a different handler, update the file and method accordingly.

    • In the sample code, you must set region and bucket based on your requirements.

  5. Click Test Function.

    After the function is executed, view the returned result. The result is put object.

Örnek 3: Harici bir komut çağırma

A Node.js program can also create a fork process to call external commands. For example, you can use the child_process module to call the Linux ls -l command and list the files in the current directory. The following code provides an example.

ES modülü

Not

This example runs only in Node.js 18 and later runtimes.

'use strict';

import { exec } from 'child_process';
import { promisify } from 'util';

const execPromisify = promisify(exec);
export const handler = async (event, context) => {
  try {
    const { stdout, stderr } = await execPromisify("ls -l");
    console.log(`stdout: ${stdout}`);
    if (stderr !== "") {
      console.error(`stderr: ${stderr}`);
    }
    return stdout;
  } catch (error) {
    console.error(`exec error: ${error}`);
    return error;
  }
}

CommonJS modülü

Not

This code supports one-click deployment. You can deploy this code to Function Compute (FC) with a single click.start-fc3-nodejs-exec

'use strict';

var exec = require('child_process').exec;
exports.handler = (event, context, callback) => {
  console.log('start to execute a command');
  exec("ls -l", function(error, stdout, stderr){
    callback(null, stdout);
});
}

Örnek 4: HTTP tetikleyici kullanarak işlev çağırma

Örnek kod

Use the URL provided by the HTTP trigger to call the function. The following code is an example.

  • If the Authentication Method for the HTTP trigger is set to No Authentication, use Postman or a curl command to call the function. For more information, see Procedure.

  • If the Authentication Method for the HTTP trigger is set to Signature Authentication, JWT authentication or Bearer authentication, use the corresponding authentication method to call the function. For more information, see Authentication.

For information about the request and response payload formats for calls made by HTTP triggers, see Call a function using an HTTP trigger.

ES modülü

Not

This example is supported only in Node.js 18 or later runtimes.

'use strict';

export const handler = async (event, context) => {
  const eventObj = JSON.parse(event);
  console.log(`receive event: ${JSON.stringify(eventObj)}`);

  let body = 'Hello World!';
  // get http request body
  if ("body" in eventObj) {
    body = eventObj.body;
    if (eventObj.isBase64Encoded) {
      body = Buffer.from(body, 'base64').toString('utf-8');
    }
  }
  console.log(`receive http body: ${body}`);

  return {
    'statusCode': 200,
    'body': body
  };
}

CommonJS modülü

Not

This sample code supports one-click deployment. You can deploy this code to Function Compute (FC) with a single click.start-fc3-nodejs-http

'use strict';
exports.handler = (event, context, callback) => {
  const eventObj = JSON.parse(event);
  console.log(`receive event: ${JSON.stringify(eventObj)}`);

  let body = 'Hello World!';
  // get http request body
  if ("body" in eventObj) {
    body = eventObj.body;
    if (eventObj.isBase64Encoded) {
      body = Buffer.from(body, 'base64').toString('utf-8');
    }
  }
  console.log(`receive http body: ${body}`);

  callback(null, {
    'statusCode': 200,
    'body': body
  });
}

Ön koşullar

A function that uses the Node.js runtime and an HTTP trigger are created based on the preceding examples. For more information, see Create an event-triggered function and Configure an HTTP trigger. If you want to specify the code as an ES module, select Node.js 18 or Node.js 20 for the runtime when you create the function.

Yordam

  1. Log on to the Function Compute console. In the navigation pane on the left, choose Function Management > Functions.

  2. In the top navigation bar, select a region. On the Functions page, click the target function.

  3. On the function details page, click the Triggers tab. On the Triggers page, obtain the public endpoint of the HTTP trigger.

  4. Run the following command in a curl tool to call the function.

    curl -i "https://test-nodejs-dlgxxr****.cn-shanghai.fcapp.run" -d 'Hello World!'

    In the preceding command, https://test-nodejs-dlgxxr****.cn-shanghai.fcapp.run is the public endpoint of the HTTP trigger.

    The following response is returned.

    HTTP/1.1 200 OK
    Access-Control-Expose-Headers: Date,x-fc-request-id
    Content-Disposition: attachment
    Content-Length: 12
    Content-Type: text/html; charset=utf-8
    Etag: W/"c-Lve95gjOVATpfV8EL5X4nxwjKHE"
    X-Fc-Request-Id: 1-65d866a8-15d8796a-cb9b4feb69ca
    X-Powered-By: Express
    Date: Fri, 23 Feb 2024 09:34:34 GMT
    
    Hello World!

Örnek 5: HTTP tetikleyici kullanarak dosya indirme

Örnek kod

To return an image, a compressed package, or a binary file from your code, use an HTTP trigger. The following code provides an example.

ES modülü

Not

This example is supported only in runtimes of Node.js 18 or later.

// index.mjs
'use strict';

import mime from 'mime';
import fs from 'fs/promises';
import path from 'path'; 

export const handler = async (event, context) => {
    const fileContent = 'This is a sample text file created in the code.';
    const fileName = 'sample.txt';
    const filePath = path.join('/tmp', fileName);
    
    try {
        await fs.writeFile(filePath, fileContent);
        
        const mimeType = mime.getType(filePath);
        if (!mimeType) {
            throw new Error('Unable to determine MIME type');
        }
        
        const fileData = await fs.readFile(filePath);
        const fileBase64 = Buffer.from(fileData).toString('base64');
        
        const fcResponse = {
            'statusCode': 200,
            'headers': {
                'Content-Type': mimeType,
                'Content-Disposition': `attachment; filename="${fileName}"`,
            },
            'body': fileBase64,
            'isBase64Encoded': true
        };
        
        console.log('File generated and fetched successfully.');
        return fcResponse;
    } catch (err) {
        console.error(err);
        return {
            'statusCode': 500,
            'body': err.message
        };
    }
};

CommonJS modülü

// index.js
'use strict';
const mime = require('mime');
const fs = require('fs');
const path = require('path');

exports.handler = async (event, context, callback) => {

    const fileContent = 'This is a sample text file created in the code.';
    const fileName = 'sample.txt';
    const filePath = path.join('/tmp', fileName);
    try {
        fs.writeFileSync(filePath, fileContent);

        const mimeType = mime.getType(filePath);
        if (!mimeType) {
            throw new Error('Unable to determine MIME type');
        }

        const fileData = fs.readFileSync(filePath);
        const fileBase64 = Buffer.from(fileData).toString('base64');

        const fcResponse = {
            'statusCode': 200,
            'headers': {
                'Content-Type': mimeType,
                'Content-Disposition': `attachment; filename="${fileName}"`,
            },
            'body': fileBase64,
            'isBase64Encoded': true
        };

        console.log('File generated and fetched successfully.');
        callback(null, fcResponse);
    } catch (err) {
        console.error(err);
        callback(null, {
            'statusCode': 500,
            'body': err.message
        });
    }
};

Ön koşullar

Create a function that uses the Node.js runtime and an HTTP trigger based on the preceding examples. For more information, see Create an event-triggered function and Configure an HTTP trigger. If you want to specify the code as an ES module, set the runtime to Node.js 18 or Node.js 20 when you create the function.

Yordam

  1. Log on to the Function Compute console. In the navigation pane on the left, choose Function Management > Functions.

  2. In the top navigation bar, select a region. On the Functions page, click the target function.

  3. On the function details page, click the Code tab, and then choose to open a terminal window. Run the npm install mime@2 command to install the mime library. After the installation is complete, click Deploy.

  4. On the Trigger tab of the function, obtain the Internet Endpoint of the HTTP trigger. Copy the URL to your browser and press Enter.

    After you press Enter, the function is triggered. If the function runs successfully, the file is downloaded to your local machine.