im trying use the chrome driver, with selenium in the firebase cloud functions.
while deploying the index.js file on to a local host, using the terminal cmd
'firebase serve --only functions' from the functions folder(which has the chromedriver file, every thing work like in supposed to, im getting a response.
But,
when I deploying the index.js file to the firebase real servers using the
'firebase deploy --only functions' ,
and then trigger the function from my app, or from a url,
im getting an error in the firebase cloud functions logs telling me
'Function execution took 1774 ms, finished with status: 'crash' '
so since there were not details about what was causing this 'crash' I uses the consoled.log() function, and printed each line that was executed successfully.
this lead me into the line of
let driver = await new Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().headless().windowSize(screen)).build();
its seems like in the firebase cloud function I can't for some reason create a chrome driver successfully , although in the local host version, it's working as expected.
here the full code of the function:
exports.initializedChromeDriver = functions.https.onRequest((request, response) => {
async function start_chrome_driver() {
functions.logger.info('Hello logs!', {structuredData: true});
console.log("did enter the function")
const dic = {};
const google_site = "https://www.gooogle.com";
const { WebDriver } = require('selenium-webdriver');
const {Builder, By} = require('selenium-webdriver');
console.log("did creat WebDriver,Builder, By, constans")
const chrome = require('selenium-webdriver/chrome');
console.log("chrome constans was created")
const screen = {
width: 1024,
height: 1024
};
let driver = await new Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().headless().windowSize(screen)).build();
console.log("driver was set");
await driver.get(google_site);
console.log("succ loading google");
return "succ loading google"
}
const p = start_chrome_driver().then((value,reject) => {
dic['status'] = 200;
dic['data'] = {"message": value};
response.send(dic);
});
and here are the logs in the firebase cloud console:
UPDATE
well after searching for answers in the web, ,i found that I didn't have a suitable 'driver' for linux systems,
so I replace the chrome driver for mac(which work on my machine, on the local host version),
with a chrome driver, for linux. and try again, well that doesn't work either , but at lest I was getting a new log with an Error, not just a 'crash' , here it his:
so now I know that I need to install the chrome browser binary for linux on the project,
any ideas to how can I do this, Im trying to install the chrome binary driver on to my project in firebase, there a few ways im trying now, like installing the chrome binary using the google shell some how, any help or idea to I do does, even so, I don't sure that after the binary will be install , this will be it, and the driver will work on the firebase servers..
Related
`
//soldity is synchronous lang
const ethers = require("ethers");
const fs = require("fs-extra");
async function main() {
//http://127.0.0.1:7545
const provider = new ethers.providers.JsonRpcProvider(
"http://127.0.0.1:7545"
);
const wallet = new ethers.Wallet(
"5248c9dfa1d4fb6369c105999f1362867d6acd5cf1dee7ef949870231520fa4f",
provider
);
const abi = fs.readFileSync("./SimpleStorage_sol_SimpleStorage.abi", "utf8");
const binary = fs.readFileSync(
"./SimpleStorage_sol_SimpleStorage.bin",
"utf8"
);
const contractFactory = new ethers.ContractFactory(abi, binary, wallet);
console.log("Deploying, please wait...");
const contract = await contractFactory.deploy(); //stop here and wait for the contract to deploy
console.log(contract);
}
main()
.then(() => ProcessingInstruction.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
`
The error is -
Error: could not detect network (event="noNetwork", code=NETWORK_ERROR, version=providers/5.7.2)
at Logger.makeError (/root/hh-fcc/ethers-simple-storage-fcc/node_modules/#ethersproject/logger/lib/index.js:238:21)
at Logger.throwError (/root/hh-fcc/ethers-simple-storage-fcc/node_modules/#ethersproject/logger/lib/index.js:247:20)
So, I am working with JavaScript and solidity and developing a contract. While deploying the contract on a ganache network using node (all code in VS), I am experiencing this network error. PLeasee help! I am trying to learn and have been trying to solve this. Below is the code.
I had the same problem using WSL subsystem (don't know if it's your case) because my ganache was running on windows while VScode was running on WSL.
I solved the problem using the terminal to installe ganache on WSL:
npm install -g ganache
Then run ganache:
ganache
It will give you some Private Keys, use one of them for your code, and then it show the IP that you have to use in your code:
RPC Listening on 127.0.0.1:3456 //or something similar
Keep ganache running in this terminal and open another one to run "node deploy.js"
Because Ganache is not connected to the WSL enviroment. So, go to the setting of the Ganache and choose the WSL as the server HOSTNAME.Finally, change the RPC in your code. Then it will be done.
let provider = new ethers.providers.JsonRpcProvider(
"HTTP://172.20.80.1:7545"
);
You might be running this from a WSL terminal, I tried running node deploy.js through windows PowerShell or Command prompt and it worked.
Open Your files in vs code without WSL enviornment and then run in terminal it will work because we have installed ganache in windows not in linux
Preamble
To start off, I'm not a developer; I'm just an analyst / product owner with time on their hands. While my team's actual developers have been busy finishing off projects before year-end I've been attempting to put together a very basic API server in Node.js for something we will look at next year.
I used Swagger to build an API spec and then used the Swagger code generator to get a basic Node.js server. The full code is near the bottom of this question.
The Problem
I'm coming across an issue when writing out to a log file using the fs module. I know that the ENOENT error is usually down to just specifying a path incorrectly, but the behaviour doesn't occur when I comment out the Swagger portion of the automatically generated code. (I took the logging code directly out of another tool I built in Node.js, so I'm fairly confident in that portion at least...)
When executing npm start, a few debugging items write to the console:
"Node Server Starting......
Current Directory:/mnt/c/Users/USER/Repositories/PROJECT/api
Trying to log data now!
Mock mode: disabled
PostgreSQL Pool created successfully
Your server is listening on port 3100 (http://localhost:3100)
Swagger-ui is available on http://localhost:3100/docs"
but then fs throws an ENOENT error:
events.js:174
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open '../logs/logEvents2021-12-24.log'
Emitted 'error' event at:
at lazyFs.open (internal/fs/streams.js:277:12)
at FSReqWrap.args [as oncomplete] (fs.js:140:20)
Investigating
Now normally, from what I understand, this would just mean I've got the paths wrong. However, the file has actually been created and the first line of the log file has been written just fine
My next thought was that I must've set the fs flags incorrectly, but it was set to 'a' for append:
var logsFile = fs.createWriteStream(__logdir+"/logEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Log File to location: %s \nWith error description: %s',__logdir, err);
});
Removing Swagger Code
Now here's the weird bit: if I remove the Swagger code, the log files write out just fine and I don't get the fs exception!
This is the specific Swagger code:
// swaggerRouter configuration
var options = {
routing: {
controllers: path.join(__dirname, './controllers')
},
};
var expressAppConfig = oas3Tools.expressAppConfig(path.join(__dirname, '/api/openapi.yaml'), options);
var app = expressAppConfig.getApp();
// Initialize the Swagger middleware
http.createServer(app).listen(serverPort, function () {
console.info('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
console.info('Swagger-ui is available on http://localhost:%d/docs', serverPort);
}).on('error',console.error);
When I comment out this code, the log file writes out just fine.
The only thing I can think that might be happening is that somehow Swagger is modifying (?) the app's working directory so that fs no longer finds the same file?
Full Code
'use strict';
var path = require('path');
var fs = require('fs');
var http = require('http');
var oas3Tools = require('oas3-tools');
var serverPort = 3100;
// I am specifically tried using path.join that I found when investigating this issue, and referencing the app path, but to no avail
const __logdir = path.join(__dirname,'./logs');
//These are date and time functions I use to add timestamps to the logs
function dateNow(){
var dateNow = new Date().toISOString().slice(0,10).toString();
return dateNow
}
function rightNow(){
var timeNow = new Date().toTimeString().slice(0,8).toString();
return "["+timeNow+"] "
};
console.info("Node Server Starting......");
console.info("Current Directory: " + __dirname)
// Here I create the WriteStreams
var logsFile = fs.createWriteStream(__logdir+"/logEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Log File to location: %s \nWith error description: %s',__logdir, err);
});
var errorsFile = fs.createWriteStream(__logdir+"/errorEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Error Log File to location: %s \nWith error description: %s',__logdir, err);
});
// And create an additional console to write data out:
const Console = require('console').Console;
var logOut = new Console(logsFile,errorsFile);
console.info("Trying to log data now!") // Debugging logging
logOut.log("========== Server Startup Initiated ==========");
logOut.log(rightNow() + "Server Directory: "+ __dirname);
logOut.log(rightNow() + "Logs directory: "+__logdir);
// Here is the Swagger portion that seems to create the behaviour.
// It is unedited from the Swagger Code-Gen tool
// swaggerRouter configuration
var options = {
routing: {
controllers: path.join(__dirname, './controllers')
},
};
var expressAppConfig = oas3Tools.expressAppConfig(path.join(__dirname, '/api/openapi.yaml'), options);
var app = expressAppConfig.getApp();
// Initialize the Swagger middleware
http.createServer(app).listen(serverPort, function () {
console.info('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
console.info('Swagger-ui is available on http://localhost:%d/docs', serverPort);
}).on('error',console.error);
In case it helps, this is the project's file structure . I am running this project within a WSL instance in VSCode on Windows, same as I have with other projects using fs.
Is anyone able to help me understand why fs can write the first log line but then break once the Swagger code gets going? Have I done something incredibly stupid?
Appreciate the help, thanks!
Edit: Tried to fix broken images.
Found the problem with some help from a friend. The issue boiled down to a lack of understanding of how the Swagger module works in the background, so this will likely be eye-rollingly obvious to most, but keeping this post around in case anyone else comes across this down the line.
So it seems that as part of the Swagger initialisation, any scripts within the utils folder will also be executed. I would not have picked up on this if it wasn't pointed out to me that in the middle of the console output there was a reference to some PostgreSQL code, even though I had taken all reference to it out of the main index.js file.
That's when I realised that the error wasn't actually being generated from the code posted above: it was being thrown from to that folder.
So I guess the answer is don't add stuff to the utils folder, but if you do, always add a bunch of console logging...
Edit: I'm changing the question to suit my current understanding of the problem which has changed significantly.
Original Title: Nodegit seems to be asking for wrong credentials on push
When trying to push using nodegit nothing seems to work on Windows (while they work fine on Linux).
Using SSH
sshKeyFromAgent - error authenticating: failed connecting agent
sshKeyNew - credentials callback is repeatedly (looks like an infinite loop
but I can't be sure)
sshKeyMemoryNew: credentials is called twice and then node exits with no diagnostic (the exit and beforeExit events on process aren't signalled)
Using HTTPS
userpassPlaintextNew: [Error: unknown certificate check failure] errno: -17
Original question follows.
I'm trying to get nodegit to push and the following question seems to address this situation. However I'm not able to get it to work.
I've cloned a repository using SSH and when I try to push, my credentials callback is being called with user git and not motti (which is the actual git user).
try {
const remote = await repository.getRemote("origin");
await remote.push(["refs/head/master:refs/heads/master"], {
callbacks: {
credentials: (url, user) => {
console.log(`Push asked for credentials for '${user}' on ${url}`);
return git.Cred.sshKeyFromAgent(user);
}
}
});
}
catch(err) {
console.log("Error:", err);
}
I get the following output:
Push asked for credentials for 'git' on git#github.[redacted].net:motti/tmp.git
Error: { Error: error authenticating: failed connecting agent errno: -1, errorFunction: 'Remote.push' }
If I try to hardcode motti to the sshKeyFromAgent function the error changes to:
Error: { Error: username does not match previous request errno: -1, errorFunction: 'Remote.push' }
This my first time trying to programmatically use git so I may be missing something basic...
Answer for some questions from comments:
I'm running on windows 10
node v8.9.4
git version 2.15.0.windows.1
nodegit version 0.24.1
the user running node is my primary user which when I use for git in command line works correctly
Instead of using git.Cred.sshKeyFromAgent - you could use git.Cred.sshKeyNew and pass your username / keys along.
const fs = require('fs');
// ...
const username = "git";
const publickey = fs.readFileSync("PATH TO PUBLIC KEY").toString();
const privatekey = fs.readFileSync("PATH TO PRIVATE KEY").toString();
const passphrase = "YOUR PASSPHRASE IF THE KEY HAS ONE";
const cred = await Git.Cred.sshKeyMemoryNew(username, publickey, privatekey, passphrase);
const remote = await repository.getRemote("origin");
await remote.push(["refs/head/master:refs/heads/master"], {
callbacks: {
credentials: (url, user) => cred
}
});
You need to run an ssh agent locally and save your password there. Follow these steps to make it work:
Enable the ssh agent locally (automatically runs on OS X): https://code.visualstudio.com/docs/remote/troubleshooting#_setting-up-the-ssh-agent
Run 'ssh-add' in the same CLI as you're running your nodegit actions and enter your passphrase
I hope this helps because I also struggled a lot with it and it can be very frustrating.
Question: How can I run git push from node.js with passphrase.
I'm trying to build a small module where I need to run git push from node.js to a remote repo, but I'm getting an error when I with from node.js exec but not from the terminal.
My code.
./command.ts
import * as util from 'util';
const exec = util.promisify(require('child_process').exec);
export default function command(command: string): Promise<string> {
return exec(command, {cwd: process.cwd()}).then((resp) => {
const data = resp.stdout.toString().replace(/[\n\r]/g, '');
return Promise.resolve(data);
});
}
./index.ts
import command from './command';
async function init() {
try {
await command('git add .');
await command('git commit -m "my commit" ');
conat result = await command('git push');
} catch (e) {
console.log(e);
}
}
init();
and when I run ts-node ./index.ts I get the following error.
Error: Command failed: git push
git#hostname.org: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
But when I run git push from the terminal I get prompt with the passphrase and it works.
Any idea on how to solve this issue, is there a way to run git push with passphrase using node.js?
bear in mind that I will love to fix this without any external libs.
Thanks in advance.
As described here, check if the same program works when:
ssh-agent is launched
your key is ssh-add'ed
Not only the prompt should no longer query for your passphrase (now cached by the agent), but your script might benefit from that cache as well.
You may need to add env: process.env to your exec() options if your key is loaded into an ssh-agent process. There are some environment variables ssh-agent exports that other processes use to find ssh-agent to access its keys.
I am trying to learn Appium, using the instructions given in the documentation:
http://appium.io/docs/en/about-appium/getting-started/?lang=en
I have put this code into a file called AppiumTest.js
const wdio = require('webdriverio');
const opts = {
port: 4723,
desiredCapabilities: {
platformName: "Android",
platformVersion: "8.0",
deviceName: "Pixel_API_26",
app: "C:/Users/SStaple/AppData/Local/Android/Sdk/ApiDemos-debug.apk",
automationName: "UiAutomator2"
}
};
const client = wdio.remote(opts);
client
.init()
.click("~App")
.click("~Alert Dialogs")
.back()
.back()
.end();
I am running it from the Node.js command prompt, using the command: node AppiumTest.js, after starting the Appium Server. It was also necessary to have an Android 8 emulator running.
(Appium Server v1.7.1)
I am getting an output in the Appium Server window. There are a number of errors. The first error shown is this:
Error "Command 'C\:\\Users\\SStaple\\AppData\\Local\\Android\\Sdk\\build-tools\\26.0.2\\aapt.exe d badging C\:\\Users\\SStaple\\AppData\\Local\\Programs\\appium-desktop\\resources\\app\\node_modules\\appium\\node_modules\\appium-uiautomator2-driver\\uiautomator2\\appium-uiautomator2-server-v0.1.8.apk' exited with code 1" while getting badging info
I have tried running this command on its own in the Command Prompt:
C:\Users\SStaple\AppData\Local\Android\Sdk\build-tools\26.0.2\aapt.exe d badging C:\Users\SStaple\AppData\Local\Programs\appium-desktop\resources\app\node_modules\appium\node_modules\appium-uiautomator2-driver\uiautomator2\appium-uiautomator2-server-v0.1.8.apk
The result I get here is this:
W/zipro (13656): Error opening archive C:\Users\SStaple\AppData\Local\Programs\appium-desktop\resources\app\node_modules\appium\node_modules\appium-uiautomator2-driver\uiautomator2\appium-uiautomator2-server-v0.1.8.apk: Invalid file
ERROR: dump failed because no AndroidManifest.xml found
Any ideas?
Update 28/12/2017 - I found the solution!
The file in question looked suspect. It was 0Kb in size!
I downloaded the apk file from https://github.com/appium/appium-uiautomator2-server/releases and used that instead.
This one is 1,518 KB in size.
(Apparently there is some problem with npm not putting that apk file into the right place while beta is installed.)
Having fixed that, I can move on to the next problem!
Its a known issue with apk signing.
You can start with trying to update dependencies:
npm install appium-uiautomator2-driver
npm install appium-adb
If it didn't help, there is more you can try (but that was for Linux):
modify
./node-v6.11.4-linux-armv7l/lib/node_modules/appium/node_modules/appium-adb/build/lib/tools/apk-signing.js so it would return a true even if it looks not signed.
case 20:
context$1$0.prev = 20;
context$1$0.t0 = context$1$0’catch’;
_loggerJs2[‘default’].debug(“App not signed with debug cert.”);
return context$1$0.abrupt(‘return’, true);