Reputation: 12320
I have below AWS lambda method
NodeJS 8.10.0
// 'use strict';
var fs = require("fs");
class ReadFile{
constructor(file){
if(undefined == file){
this.file = "./index.html";
}
}
content(){
var buff = fs.readFileSync(this.file);
return Buffer.from(buff, 'base64').toString('ascii');
}
}
exports.handler = function (event, context, callback) {
var f = new ReadFile(event.file);
callback(null, f.content());
// callback(null,f.content());
};
I got Syntax error
But Same method is working when I define it in handlers without class like below
exports.handler = function (event, context, callback) {
if (undefined === event.file) {
event.file = "index.html";
}
var cn = fs.readFileSync(event.file);
callback(null, Buffer.from(cn, 'base64').toString('ascii'));
// callback(null,f.content());
};
Got error
{errorMessage=RequestId: a51e4f417 Process exited before completing request}
Upvotes: 0
Views: 691
Reputation:
It happens because your function finish before than your callback ends its execution. You'll need to put the callback in a setTimeOut to finish its execution. This happens because nodeJS uses blocking execution and the callback doesn't return something.
Try with the following structure:
exports.handler = function (event, context, callback) {
if (undefined === event.file) {
event.file = "index.html";
}
var cn = fs.readFileSync(event.file);
setTimeout(() => { //Timeout to execute the callback
callback(null, Buffer.from(cn, 'base64').toString('ascii'));
// callback(null,f.content());
}, 10000);
};
As you can see, I added callback in a timeout to load it. This method become the code to Non-blocking and your main function won't finish without its callback.
If you want to use the first structure, just put all your code in main handler and your callback in a timeout like the example.
Upvotes: 0
Reputation: 4630
Looks like problem was in your constructor code. I think that your missing else
part of condition. So try to replace
constructor(file){
if(undefined == file){
this.file = "./index.html";
}
}
to
constructor(file){
if(undefined == file){
this.file = "./index.html";
}
else {
this.file = file;
}
}
Upvotes: 1