- Print
- PDF
Node.js
- Print
- PDF
Available in Classic and VPC
This section describes how to create and use Node.js actions in a variety of ways, and includes application examples.
Create action
A code written in JavaScript may contain multiple functions, but the main function must be declared as the starting point of a program. With this taken into account, the following is a simple example code hello.js in JavaScript, printing Hello World along with a name and location.
function main(params) {
var name = params.name || 'World';
var place = params.place || 'Naver';
return {payload: 'Hello, ' + name + ' in ' + place + '!'};
}
The following is the creation process of an action called "hello" in the console, using the code written above.
Create action using Node.js module packaging
When writing codes, you may need to create multiple files or use libraries beyond those provided by default. In this case, you can package related files into a single module and create an action using the packaged file. To create an action using Node.js module packaging, take the following steps:
Create a package.json file in json format.
{ "name": "my-action", "main": "index.js", "dependencies" : { "left-pad" : "1.1.3" } }
Create a simple index.js file that uses the left-pad.
function myAction(args) { const leftPad = require("left-pad") const lines = args.lines || []; return { padded: lines.map(l => leftPad(l, 30, ".")) } } exports.main = myAction;
Install the left-pad library using npm install command and create a ZIP file.
$ npm install $ zip -r action.zip *
- The package.json file must be located in the root of the ZIP file.
Create an action using the ZIP file from step 3 in the console.
Run the action in the console and check the results.
Currently, actions do not run properly if installed dependencies include binary files when running npm install
.
Create asynchronous action
You can create actions that run asynchronously. For JavaScript functions that run asynchronously, activation results may need to be returned after the main
function ends. This can be resolved by returning a Promise within the action. The following is an example code for creating an asynchronous action called asyncAction:
When running like the example code, be careful because it may cause excessive charges due to resource monopolization.
function main(args) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({ done: true });
}, 2000);
})
}
- The
main
function returns a Promise, indicating the action is not yet complete and will complete in the future. - The Callback runs after 2 seconds by the
setTimeout
function. The Promise is fulfilled when theresolve()
function runs in the Callback, and the action completes normally. Ifreject()
function is called, it indicates the action completed abnormally. - Create and run asyncAction in the console, then check the action run results to see approximately 2 seconds difference between start and end Timestamps.