I would like to use the ES6 class syntax in AWS Lambda using Node 6.10, but I cannot get it to work:
class widget {
constructor(event, context, callback) {
callback(null, `all seems well!`);
}
}
// module.exports.handler = widget; // "Process exited before completing request"
module.exports.handler = new widget(); // "callback is not a function"
Has anyone had success with using the class syntax? The class constructor does not get seen as a handler function apparently.
The Node14 Lambda runtime recently got support to ES6 modules and top-level await. Using them, the handler can support more modern structures. Previously, the handler had to use CommonJS: // commonjs // import is via require const dep = require("./dep.
You can run JavaScript code with Node. js in AWS Lambda. Lambda provides runtimes for Node. js that run your code to process events.
AWS Lambda natively supports Java, Go, PowerShell, Node. js, C#, Python, and Ruby code, and provides a Runtime API which allows you to use any additional programming languages to author your functions.
You are not following the API that Lambda expects. As the documentation says, it expects
exports.myHandler = function(event, context, callback) {};
which it would then call with
const handlers = require('your-module');
handlers();
The issue here is that ES6 classes need to be created with new
. Since the Lambda API says it expects a function, it expects a callable function, not a constructable function. If you want to use a class, you'd need to export a function, e.g.
class widget {
constructor(event, context, callback) {
callback(null, `all seems well!`);
}
}
exports.myHandler = function(event, context, callback) {
new widget(event, context, callback);
};
To answer to your question, yes, you can use ES6 classes with the Node 6 Lambda functions. But this code is not going to work.
The lambda handler is not going to call new
on your class so your constructor won't fire if you just pass
module.exports.handler = widget;
It will call widget(event, context, callback)
. If you call new
before you pass it it off, then you don't yet have the callback reference from the handler. You are essentially creating a new object with no initialized values. You're calling new widget()
but you're not passing anything it and then you are passing this new instance for the handler to call.
There's no reason on earth (as far as I can tell) to do this, but you could:
class widget extends Function {
constructor(){
super('...args', 'return this.__call__(...args)');
return this.bind(this);
}
__call__(event, context, callback) {
callback(null, "Dude, this is wierd.")
}
}
exports.handler = new widget()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With