I am trying to read a file .yml inside an AWS Lambda function (Node 6.10.0).
console.log(__dirname + '/gameOptions.yml');
console.log(path.resolve('./gameOptions.yml'));
console.log(path.resolve('/gameOptions.yml'));
console.log('./gameOptions.yml');
console.log(process.cwd() + '/api/lib/gameOptions.yml');
let doc = yaml.safeLoad(fs.readFileSync(path.resolve('./gameOptions.yml'), 'utf8'));
I have tried all possibles ways to do it, but always get ENOENT: no such file or directory.
The file is at the same folder and it is an .yml so require('') also doesnt work.
The results for the above code are:
/Users\marcus\Documents\Workspace\proak-api\proak-api\api\lib/gameOptions.yml
/var/task/gameOptions.yml
/gameOptions.yml
./gameOptions.yml
/var/task/api/lib/gameOptions.yml
And it works locally.
To solve this you need to care of two things:
Optimize If you are using something to minify the code, E.g. serverless-plugin-optimize:
Include the file to not be minified.
myLambda:
handler: mySubFolder/myLambda.handler
optimize:
includePaths: ['mySubFolder/myFile.json']
Resolve the path.
path.resolve(process.env.LAMBDA_TASK_ROOT, '_optimize', process.env.AWS_LAMBDA_FUNCTION_NAME, 'mySubFolder/myFile.json')
If you dont use minify, you also need to require the .yml file into the Lambda, to compile into the function.
Require require('file.yml') gives you an error. So you let to:
var fs = require('fs')
, yaml = require('js-yaml');
require.extensions['.yaml'] =
require.extensions['.yml'] = function(module, filename) {
var content = fs.readFileSync(filename, 'utf8');
// Parse the file content and give to module.exports
content = yaml.load(content);
module.exports = content;
};
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