This topic describes the structural characteristics of event handlers and provides examples on how to use event handlers in Node.js.
Event handler signature
ECMAScript modules are supported by Function Compute in Node.js 18 and later. For Node.js 16 and earlier versions, Function Compute supports only CommonJS modules. For more information, see Specify an ECMAScript module as the handler.
The following sample code describes the signature for an event handler.
Node.js 18 and later
ECMAScript module
// index.mjs
export const handler = async (event, context) => {
console.log("event: \n" + event);
return "Hello World!";
};
CommonJS module
// index.js
exports.handler = async function(event, context) {
console.log("event: \n" + event);
return "Hello World!";
};
Node.js 16 and earlier
// index.js
exports.handler = async function(event, context, callback) {
console.log("event: \n" + event);
callback(null, 'hello world');
};
Parameter description:
handler
indicates the method name, which corresponds to the value of the Handler parameter configured in the Function Compute console. For example, if you set Handler to index.handler
when you create a function, Function Compute loads the handler
function defined in index.js
and starts to execute code.
Function Compute runtimes pass request parameters to the handler. The first parameter is the event
object, which contains the request payload information. The event
object is of the Buffer type. You can convert it to another object type based on your business requirements. The second parameter is a context
object that provides context information during invocations. For more information, see Context.
We recommend that you use Async/Await instead of
callback
if you use Node.js 18 or later.Function Compute converts the returned result based on the type of the returned value.
Buffer type: The result is returned without conversion.
Object type: The result is converted into the JSON format.
Other types: The results are returned as strings.
Async/Await
We recommend that you use Async/Await in Node.js 18 or later. Async/Await is a simple and easy-to-read way to write asynchronous code in Node.js without nested callbacks or method chaining.
If you use Node.js 16 or earlier, you must explicitly use callback
to send responses. Otherwise, a request timeout error occurs.
Compared with callback
, Async/Await delivers the following benefits:
Better readability: The code in Async/Await mode is more linear and synchronous, and easier to understand and maintain. It prevents nests of high levels and makes the code structure clearer.
Easy to debug and handle errors: You can use try-catch blocks to catch and handle errors in asynchronous operations more easily. Error stacks can be easily located and traced.
Higher efficiency: In most cases, callback functions must switch between different parts of code. Async/Await can reduce the number of context switches, thereby improving code efficiency.
Example 1: Parse JSON-formatted parameters
Sample code
When you pass JSON-formatted parameters into functions of Function Compute, Function Compute passes through the parameters, and you need to parse the parameters in the code. The following sample code provides an example on how to parse a JSON-formatted event.
ECMAScript module
This example supports only Node.js 18 or later.
export const handler = async (event, context) => {
var eventObj = JSON.parse(event.toString());
return eventObj['key'];
};
CommonJS module
exports.handler = function(event, context, callback) {
var eventObj = JSON.parse(event.toString());
callback(null, eventObj['key']);
};
Prerequisites
A Node.js function is created. For more information, see Create a function. If you want to specify the code as an ECMAScript module, you must select Node.js 18 or Node.js 20 as the runtime when you create a function.
Procedure
Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.
In the top navigation bar, select a region. On the Services page, click the desired service.
On the Functions page, click the name of the desired function. On the Function Details page that appears, click the Code tab.
On the Code tab, enter the preceding sample code in the code editor and click Deploy.
NoteIn the preceding sample code, the handler is the
handler
method inindex.js
orindex.mjs
. If you specify a different handler, use the actual file and method.On the Code tab, click the icon next to Test Function, select Configure Test Parameters from the drop-down list, configure the following test parameters, and then click OK.
{ "key": "value" }
Click Test Function.
After the function is executed, the execution result is returned. The execution result is
value
.
Example 2: Read and write OSS resources by using a temporary AccessKey pair
Sample code
You can use a temporary AccessKey pair that is provided by Function Compute to access Object Storage Service (OSS). This section provides sample code.
ECMAScript module
This example supports only Node.js 18 or later.
// 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 {
// Upload an object to OSS. object indicates the name of the object in OSS. localfile indicates the path of the on-premises file.
const uploadResult = await ossClient.put('myObj', Buffer.from('hello, fc', "utf-8"));
console.log('upload success, ', uploadResult);
return "succ"
} catch (error) {
throw error
}
};
The following items describe the parameters:
context.credentials
: obtains the temporary key from the context parameter. This helps prevent hard-coding of sensitive information such as passwords in the code.myObj
: the name of the OSS object.Buffer.from('hello, fc', "utf-8")
: the uploaded object content.return "succ"
: returns succ if the upload is successful.throw err
: throws an exception if the upload fails.
CommonJS module
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-cn-shenzhen',
bucket: 'my-bucket',
});
ossClient.put('myObj', Buffer.from('hello, fc', "utf-8")).then(function (res) {
callback(null, 'succ');
}).catch(function (err) {
callback(err);
});
};
The following items describe the parameters:
context.credentials
: obtains the temporary key from the context parameter to avoid hard-coding of sensitive information such as passwords in the code.myObj
: the name of the OSS object.Buffer.from('hello, fc', "utf-8")
: the uploaded object content.callback(null, 'put object')
: returns succ if the upload is successful.callback(err): returns Err if the upload fails.
Prerequisites
A role that has the permissions to access OSS is configured for the service. For more information, see Grant Function Compute permissions to access other Alibaba Cloud services.
A function that runs in a Node.js runtime is created. For more information, see Create a function. If you want to specify the code as an ECMAScript module, you must select Node.js 18 or Node.js 20 as the runtime when you create a function.
Procedure
Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.
In the top navigation bar, select a region. On the Services page, click the desired service.
On the Functions page, click the name of the desired function. On the Function Details page that appears, click the Code tab.
Optional. On the Code tab, click WebIDE in the lower part of the page. On the WebIDE page, click
. Run the following command to install ali-oss dependencies in the terminal:npm install ali-oss --save
After the installation is complete, you can see that the
node_modules
folder is generated in the code directory on the left side of WebIDE. The folder contains theali-oss
directory and other dependent libraries.On the Code tab, enter the preceding sample code in the code editor, save the code, and then click Deploy.
NoteThe request handler of the functions in the preceding sample code is the handler method in
index.js
orindex.mjs
. If you specify a different handler, use the actual file and method.In the preceding sample code, specify
region
andbucket
based on the actual values.
Click Test Function.
After the function is executed, the execution result is returned. The execution result is
succ
.
Example 3: Call external commands
You can use a Node.js program to create a fork
process to call external commands. For example, you can use the child_process
module to call the ls -l
command. After you call the command, the files in the current directory are returned. This section provides sample code.
ECMAScript module
This example supports only Node.js 18 or later.
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 module
'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);
});
}