Cannot read property 'filename' of undefined Using html-pdf with lambda - node.js

I'm experiencing problems when I try to create a PDF from HTML using Lambda Function, I'm receiving the error below:
{
"errorType": "TypeError",
"errorMessage": "Cannot read property 'filename' of undefined",
"trace": [
"TypeError: Cannot read property 'filename' of undefined",
" at execPdfToBuffer (/var/task/node_modules/html-pdf/lib/pdf.js:48:21)",
" at ChildProcess.respond (/var/task/node_modules/html-pdf/lib/pdf.js:144:5)",
" at ChildProcess.emit (events.js:314:20)",
" at ChildProcess.EventEmitter.emit (domain.js:483:12)",
" at Process.ChildProcess._handle.onexit (internal/child_process.js:276:12)"
]
}
My code is:
try{
let arq = await new Promise((res,rej)=>{
pdf.create(html,{
format: "Letter",
orientation: "portrait",
phantomPath: '/opt/phantomjs_linux-x86_64'
}).toBuffer(function(err, buffer){
if (err){
rej(false);
}else{
res(buffer);
}
});
});
const params = {
Key: 'teste.pdf',
Body: arq, // <---------
Bucket: 'temp'
};
let S3 = new AWS.S3();
let response = await S3.upload(params).promise();
if (response){
return true;
}else{
return false;
}
}catch(err){
console.log(err);
return false;
}
I've read this topic: html-pdf package is not working on aws lambda
But the proposed solution didn't work for me.
Thank you in advance

In the version 3.0.1 you can set the flag localUrlAccess: true, , it will work

I ran into this issue, too. I fixed it by downgrading html-pdf from version 3.0.1 to version 2.2.0.
The release notes for the newer version are less than inspiring: "Not sure this module is even usable without installing phantomjs manually"
Perhaps there's a way to make version 3 work with lambda. But downgrading was a quick win for me.

Related

Cypress for Electron - Using FS

I am using Cypress to test my Electron application.
Since Cypress uses the browser mode, FS is not supported.
So I am getting this error:
Error in mounted hook: "TypeError: fs.existsSync is not a function"
And I found this on the documentation:
https://docs.cypress.io/api/commands/task.html#Event
So I added this on my test:
it('Sample test', () => {
cy.task('readSettingsJson', settingsFolder).then((content) => {
// This can print the JSON file contents correctly
console.log('content = ' + content)
})
})
And on my plugins/index.js:
on('task', {
readSettingsJson(foldername) {
if (!fs.existsSync(foldername)) {
fs.mkdirSync(foldername, { recursive: true })
// some command to copy the file
} else {
// This is what I am testing at this moment
return fs.readFileSync(path.join(filename, '/settings.json'), 'utf8')
}
return null
}
})
However, it doesnt seem to work. I still get the error:
Error in mounted hook: "TypeError: fs.existsSync is not a function"
And despite the test printing the json file correctly, my app still can't load the JSON file.
Am I missing anything? Help please!
Cypress support for Electron apps are in very early alpha release:
https://www.cypress.io/blog/2019/09/26/testing-electron-js-applications-using-cypress-alpha-release/
As an alternative, try using Spectron, which is the testing framework that is currently recommended by Electron team:
https://www.electronjs.org/spectron

Selenium testing with AWS Lambda Node.js 12.x - Error saying "Chromedriver not found"

I've been trying to run my Selenium tests on AWS Lambda with runtime Node.js 12.x, but I've been running into an error.
{
"errorType": "Error",
"errorMessage": "The ChromeDriver could not be found on the current PATH. Please download the latest version of the ChromeDriver from http://chromedriver.storage.googleapis.com/index.html and ensure it can be found on your PATH.",
"trace": [
"Error: The ChromeDriver could not be found on the current PATH. Please download the latest version of the ChromeDriver from http://chromedriver.storage.googleapis.com/index.html and ensure it can be found on your PATH.",
" at new ServiceBuilder (/var/task/aws-Lambda-Selenium-2.0/node_modules/selenium-webdriver/chrome.js:232:13)",
" at getDefaultService (/var/task/aws-Lambda-Selenium-2.0/node_modules/selenium-webdriver/chrome.js:321:22)",
" at Function.createSession (/var/task/aws-Lambda-Selenium-2.0/node_modules/selenium-webdriver/chrome.js:695:44)",
" at createDriver (/var/task/aws-Lambda-Selenium-2.0/node_modules/selenium-webdriver/index.js:155:33)",
" at Builder.build (/var/task/aws-Lambda-Selenium-2.0/node_modules/selenium-webdriver/index.js:662:16)",
" at Runtime.module.exports.testFn [as handler] (/var/task/aws-Lambda-Selenium-2.0/handler.js:35:32)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
I know that a similar question has been answered recently, but I've used the chrome-aws-lambda npm package and this still hasn't worked. My Lambda function has 2GB of memory at its disposal, and I've limited the time outs to 5 min. Below I have placed the code of my handler.js. Any help would be greatly appreciated.
'use strict';
module.exports.testFn = async (event, context, callback) =>
{
const webdriver = require("selenium-webdriver");
const chrome = require('selenium-webdriver/chrome');
const builder = new webdriver.Builder().forBrowser('chrome');
const chromeOptions = new chrome.Options();
const defaultChromeFlags =
[
'--headless',
'--disable-gpu',
'--disable-dev-shm-usage',
'--window-size=1280x1696',
'--no-sandbox',
'--user-data-dir=/tmp/user-data',
'--hide-scrollbars',
'--enable-logging',
'--log-level=0',
'--v=99',
'--single-process',
'--data-path=/tmp/data-path',
'--ignore-certificate-errors',
'--homedir=/tmp',
'--disk-cache-dir=/tmp/cache-dir'
];
const HEADLESS_CHROME_PATH = '/var/task/aws-Lambda-Selenium-2.0/node_modules/chrome-aws-lambda/bin/chromium.br';
chromeOptions.setChromeBinaryPath(HEADLESS_CHROME_PATH);
chromeOptions.addArguments(defaultChromeFlags);
builder.setChromeOptions(chromeOptions);
let driver = await builder.build(); // <-- program is not getting passed this line
await driver.get("https://www.google.com/");
await driver.getTitle().then(() =>
{
console.log("Page title for " + "https://www.google.com/" + " is ");
});
await driver.quit();
}

putBotAlias not working in AWS LexModelBuildingService node.js

I've been trying to replace the existing LexBot Alias(named LATEST) with a newly created bot version.
Now, according to aws documentation
When you want to update a bot alias, set the checksum field to the checksum of the most recent revision of the $LATEST version.
I can see the Alias LATEST is using bot version 12 in the Lex Console.
I have tried getting the checksum using the following (I am using getBot(...) of LexModelBuildingService to get checksum of the bot):
using Alias name itself as version i.e. LATEST.
setting versionOrAlias in getBot method params as '$LATEST'.
Hardcoding the version to 12in getBot(..).
I have used checksum from the above scenarios, but the error seems to be same as
PreconditionFailedException: The checksum value doesn't match for the resource named 'LATEST'.
Here's code snippet
async putBotAlias(botVersionResponse){
let checksum;
await this.getBot(botVersionResponse.name,'12').then(botRes=>{ // have used 12, LATEST, $LATEST with same error
console.log("Checksum For Latest: " + botRes.checksum);
checksum = botRes.checksum;
});
var params = {
botName: botVersionResponse.name,
botVersion: (parseInt(botVersionResponse.version,10)).toString(),
name: 'LATEST',
checksum : checksum
};
// checksum: checksum
console.log("Params in putBotAlias : " + JSON.stringify(params));
return new Promise((resolve,reject)=>{
this.modelBuildingService.putBotAlias(params, function(err, data) {
if (err){
reject(err);
} // an error occurred
else{
console.log("Put Alias Response :::" + JSON.stringify(data));
resolve(data);
} // successful response
});
});
}
I am really at lost here as to what version exactly it wants.
Any help is greatly appreciated.
PS: Please mention any additional required information in comments.
Apparantly I was putting checksum of 'Bot' and not of the 'BotAlias' which I was trying to put.
Updated code gets the checksum of bot Alias :
async putBotAlias(botVersionResponse,aliasName){
let checksum;
if(typeof aliasName != "undefined"){
await this.getBotAlias(botVersionResponse.name,aliasName).then(res=>{
console.log("Checksum For Latest ALIAS : " + res.checksum);
checksum = res.checksum;
}).catch((err)=>{
console.log(" Unable to getBotAlias checksum " + err);
});
}
Silly mistake, but hope it helps anyone making it. :)

Sails startDownload not working - TypeError: sails.startDownload is not a function

I am following https://sailsjs.com/documentation/reference/response-res/res-attachment
My code looks like this:
let file = require('path').resolve(document.path)
if (fs.existsSync(file)) {
this.res.attachment(document.name)
let downloading = await sails.startDownload(document.fsPath)
return exits.success(downloading)
}
Exits:
exits: {
success: {
statusCode: 200,
description: 'Document has been sent for download.'
},
}
I am getting error
TypeError: sails.startDownload is not a function
Sails version 1.1.0
Have you installed sails-hook-uploads as mentioned in the documentation you have linked to?

NodeRT - StorageFile.openAsync returns undefined fileStream, but no error

I'm just getting started with NodeRT & Electron (Windows 10). Some of the basics seem to be working, but I've quickly run up against a strange issue. Here's the code:
const {FileAccessMode, StorageFile} = require('electron').remote.require('#nodert-win10/windows.storage')
var fname = require('electron').remote.app.getPath('userData') + '\\test.jpg';
StorageFile.getFileFromPathAsync(fname, (err, storageFile) => {
if (err) return console.log(err);
storageFile.openAsync(FileAccessMode.read, (err, fileStream) => {
if (err) return console.log(err);
// fileStream is NULL HERE!
})
})
getFileFromPathAsync succeeds and the resulting storageFile is valid. However, openAsync returns an undefined fileStream and an undefined err!
Questions:
What am I doing wrong here?
In any case, why is openAsync failing silently with no error?
Thanks!
Finally, this was a bug in NodeRT when used in combo with the most recent electron builds. It is now fixed.
Props to #nadavbar for fixing this the same day that I reported it. :) NodeRT seems to play very nicely with electron now.

Resources