Error parsing triggers: Cannot find module 'firebase/firestore' - api

I am trying to run a very basic code on google api using firebase.
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
//const {Card, Suggestion} = require('dialogflow-fulfillment');
var admin = require('firebase-admin');
require("firebase/firestore");
admin.initializeApp(functions.config().firebase);
//var firestore = admin.firestore();
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
//firestore arguments defined
/* var addRef = firestore.collection('Admissions');
var feeRef = firestore.collection('Fees');
*/
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
console.log("request.body.queryResult.parameters: ", request.body.queryResult.parameters);
// Run the proper function handler based on the matched Dialogflow intent name
var intentMap = new Map();
});
It gives me a error that says
'Error parsing triggers: Cannot find module 'firebase/firestore'.Try running "npm install" in your functions directory before deploying.
When I run npm install inside the funtions directory, I get:
audited 9161 packages in 25.878s found 292 vulnerabilities (21 low,
207 moderate, 64 high) run npm audit fix to fix them, or npm
audit for details
Its been a week, I am stuck with these errors, these errors keep fluctuating based on the solution i find. But i am not able to overcome this error. Can you please check if there is something wrong I am doing, or anything else I need to try?

Just delete the node_modules folder and run npm install again. I was also stuck on this for a week. It is a corrupt file issue.

Related

Where can I find the key.json when running a BigQuery job in the terminal?

I'm trying to run the following code but I get this error
{ [Error: ENOENT: no such file or directory, open '/mypath/key.json'] }
I know it has something to do with no key.json file in the directory I'm running the code from, but where can I find this file?
I've tried searching find / -name "key.json" and using some paths there but I still get the same error. Thanks
const BigQuery = require('#google-cloud/bigquery');
const bigquery = new BigQuery({
projectId: 'XXXXX',
keyFilename: 'key.json'
});
const query = `SELECT total_amount, pickup_datetime, trip_distance
FROM \`nyc-tlc.yellow.trips\`
ORDER BY total_amount DESC
LIMIT 1;`
bigquery.createQueryJob(query).then((data) => {
const job = data[0];
return job.getQueryResults({timeoutMs: 10000});
}).then((data) => {
const rows = data[0];
console.log(rows[0]);
}).catch(e=>{
//handle exception
console.log(e)
})
;
The key.json file is the resulting file that you download in order to authenticate against GCP services. There are several methods to authenticate and one of those is using a service account. The key.json is the file that contains the credentials needed.
How you create and use the key.json file is explained here1
This is also a good guide for creating the credentials via the Console UI 2

Truffle test fails with Error: Could not find artifacts

I learn the demo: Code is come from: https://truffleframework.com/tutorials/pet-shop, when I test:
$ truffle.cmd test
Using network 'development'.
Compiling .\test\TestAdoption.sol...
TestAdoption
1) "before all" hook: prepare suite
0 passing (30s)
1 failing
1) TestAdoption
"before all" hook: prepare suite:
Error: Could not find artifacts for /E/blockchain/pet-
shop/contracts/Adoption.sol from any sources
at Resolver.require (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-resolver\index.js:37:1)
at TestResolver.require (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\testresolver.js:17:1)
at TestResolver.require (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\testresolver.js:17:1)
at dependency_paths.forEach.dependency_path (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\soliditytest.js:203:1)
at Array.forEach (<anonymous>)
at deployer.deploy.then (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\soliditytest.js:202:1)
at D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-deployer\src\deferredchain.js:20:1
at process._tickCallback (internal/process/next_tick.js:68:7)
I updated my nodejs lastest, and installed window-build-tools,it does not work.
TestAdoption.sol:
pragma solidity ^0.5.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/Adoption.sol";
contract TestAdoption {
Adoption adoption = Adoption(DeployedAddresses.Adoption());
function testUserCanAdoptPet() public {
uint returnedId = adoption.adopt(expectedPetId);
Assert.equal(returnedId, expectedPetId);
}
uint expectedPetId = 8;
address expectedAdopter = address(this);
function testGetAdopterAddressByPetId() public {
address adopter = adoption.adopters(expectedPetId);
Assert.equal(adopter, expectedAdopter, "Owner of the expected pet should be this contract");
}
function testGetAdopterAddressByPetIdInArray() public {
address[16] memory adopters = adoption.getAdopters();
Assert.equal(adopters[expectedPetId], expectedAdopter, "Owner of the expected pet should be this contract");
}
}
2_deploy_contracts.sol:
var Adoption = artifacts.require("Adoption");
module.exports = function(deployer) {
deployer.deploy(Adoption);
};
And import "truffle/Assert.sol"; vscode say: Source "truffle/Assert.sol" not found: File import callback not supported.My friend's version is 0.4.14 and work well, may be a version problem?
Here is project dir(just a demo from https://truffleframework.com/tutorials/pet-shop):
This error DOESN'T happen (currently) in the version v5.1.10 of truffle.
My full error was:
TypeError: Error parsing C:/Users/PATH/yourSmartContract.sol: Cannot destructure property 'body' of 'undefined' as it is undefined.
My solution is to downgrade the version like so:
$ npm uninstall -g truffle
$ npm install -g truffle#v5.1.10
(Developing in BC is hard because of version control and managment. Keep the good the work.)
The problem is the name of the artifact is defined according to the contract's name. This is your contract:
contract TestAdoption {
}
So;
2_deploy_contracts.sol:
// not artifactsrequire(Adoption)
var Adoption = artifacts.require("TestAdoption");
module.exports = function(deployer) {
deployer.deploy(Adoption);
};
Try these files:
1_initial_migration.js:
const Migrations = artifacts.require("Migrations");
module.exports = function(deployer) {
deployer.deploy(Migrations);
};
2_deploy_contracts.js:
const YourContractName = artifacts.require("YourContractName");
module.exports = function(deployer) {
deployer.deploy(YourContractName);
};
Tips:
Do not change the name of the files (1_initial_migration.js and 2_deploy_contracts.js);
Use the exactly name of your contract in the "2_deploy_contracts" file (if it is called BatatinhaFrita123, you need to specify BatatinhaFrita123 inside the artifacts.require()).

electron certificates network

I am trying to write a simple electron app to interface with a REST server. The server doesn't have the appropriate certificates. When I try to make a 'GET' request (using fetch()), I get the following error message:
Failed to load resource: net::ERR_BAD_SSL_CLIENT_AUTH_CERT
Fixing the certs is not currently an option. I tried to use the 'ignore-certificates-error' flag (see below). It seems like it should allow me to skip over this error, but it doesn't.
var electron = require('electron');
var app = electron.app
app.commandLine.appendSwitch('ignore-certificate-errors');
...
The result is the same error.
Questions:
I am correct in assuming this options is supposed to help here?
If so, any ideas what I am doing wrong?
Electron version: 1.2.8
Thanks!
You can update your version of electron and use this callback:
app.on('certificate-error', (event, webContents, link, error, certificate, callback) => {
if ('yourURL/api/'.indexOf(link) !== -1) {
// Verification logic.
event.preventDefault();
callback(true);
} else {
callback(false);
}
});
That you going do the fetch to your api with https.

Google Cloud Storage - Error during upload: gcs-resumable-upload.json renaming operation not permitted

I'm simply trying to follow this tutorial on how to upload files to gcs with Node and Express. But the following error keep causing my app to crash. Usually, I am able to upload one file without a problem in the first run. But I will get this error after running a few request, even with different file. When I try to upload, say 5, files at a time, this error cause my app to crash even in the first run. I see the process is trying to rename a file in the .config folder. Is it a normal behavior? If so, is there a work-around?
Window: v10.0.10586
Node: v4.3.1
Express: v4.13.1
Error: EPERM: operation not permitted, rename 'C:\Users\James Wang.config\configstore\gcs-resumable-upload.json.2873606827' -> 'C:\Users\James Wang.config\configstore\gcs-resumable-upload.json'
at Error (native)
at Object.fs.renameSync (fs.js:681:18)
at Function.writeFileSync as sync
at Object.create.all.set (C:\Users\James Wang\gi-cms-backend\node_modules\configstore\index.js:62:21)
at Object.Configstore.set (C:\Users\James Wang\gi-cms-backend\node_modules\configstore\index.js:93:11)
at Upload.set (C:\Users\James Wang\gi-cms-backend\node_modules\gcs-resumable-upload\index.js:264:20)
at C:\Users\James Wang\gi-cms-backend\node_modules\gcs-resumable-upload\index.js:60:14
at C:\Users\James Wang\gi-cms-backend\node_modules\gcs-resumable-upload\index.js:103:5
at Request._callback (C:\Users\James Wang\gi-cms-backend\node_modules\gcs-resumable-upload\index.js:230:7)
at Request.self.callback (C:\Users\James Wang\gi-cms-backend\node_modules\request\request.js:199:22)
at emitTwo (events.js:87:13)
at Request.emit (events.js:172:7)
at Request. (C:\Users\James Wang\gi-cms-backend\node_modules\request\request.js:1036:10)
at emitOne (events.js:82:20)
at Request.emit (events.js:169:7)
at IncomingMessage. (C:\Users\James Wang\gi-cms-backend\node_modules\request\request.js:963:12)
[nodemon] app crashed - waiting for file changes before starting...
UPDATE:
After setting {resumable: false} as suggested by #stephenplusplus in this post, I am no longer getting the "EPERM: operation not permitted" error.But, I start running into the { [ERROR:ETIMEDOUT] code: 'ETIMEDOUT', connection: false } error while trying to upload multiple files at a time with the largest file greater than 1.5mb. Other files get uploaded successfully.
For more information, I am able to upload files one by one when the files are no greater than ~2.5mb. If I try to upload 3 files at a time, I can only do so with files no greater than ~1.5mb.
Is the "Operation not permitted" issue as specified in the question a window specific thing, and does the timeout issue happen only after i set resumable = false?
I'm using express and multer with node.
This is the code I'm using now:
// Express middleware that will handle an array of files. req.files is an array of files received from
// filemulter.fields([{field: name, maxCount}]) function. This function should handle
// the upload process of files asychronously
function sendFilesToGCS(req, res, next) {
if(!req.files) { return next(); }
function stream(file, key, folder) {
var gcsName = Date.now() + file.originalname;
var gcsFile = bucket.file(gcsName);
var writeStream = gcsFile.createWriteStream({ resumable: false });
console.log(key);
console.log('Start uploading: ' + file.originalname);
writeStream.on('error', function(err) {
console.log(err);
res.status(501).send(err);
});
writeStream.on('finish', function() {
folder.incrementFinishCounter();
req.files[key][0].cloudStorageObject = gcsName;
req.files[key][0].cloudStoragePublicUrl = getPublicUrl(gcsName);
console.log('Finish Uploading: ' + req.files[key][0].cloudStoragePublicUrl);
folder.beginUploadNext();
});
writeStream.end(file.buffer);
};
var Folder = function(files) {
var self = this;
self.files = files;
self.reqFilesKeys = Object.keys(files); // reqFilesKeys is an array of keys parsed from req.files
self.nextInQuene = 0; // Keep track of the next file to be uploaded, must be less than reqFilesKeys.length
self.finishCounter = 0; // Keep track of how many files have been uploaded, must be less than reqFilesKeys.length
console.log(this.reqFilesKeys.length + ' files to upload');
};
// This function is used to initiate the upload process.
// It's also called in the on-finish listener of a file's write-stream,
// which will start uploading the next file in quene
Folder.prototype.beginUploadNext = function() {
// If there's still file left to upload,
if(this.finishCounter < this.reqFilesKeys.length) {
// and if there's still file left in quene
if(this.nextInQuene < this.reqFilesKeys.length) {
// upload the file
var fileToUpload = this.files[this.reqFilesKeys[this.nextInQuene]][0];
stream(fileToUpload, this.reqFilesKeys[this.nextInQuene], this);
// Increment the nextInQuene counter, and get the next one ready
this.nextInQuene++;
}
} else {
console.log('Finish all upload!!!!!!!!!!!!!!!!!!!!!!');
next();
}
};
Folder.prototype.incrementFinishCounter = function() {
this.finishCounter++;
console.log('Finished' + this.finishCounter + ' files');
};
var folder = new Folder(req.files);
// Begin upload with 3 streams
/*for(var i=0; i<3; i++) {
folder.beginUploadNext();
}*/
//Upload file one by one
folder.beginUploadNext();
}
I had the same issue with bower .. Run the following command: bower cache clean --allow-root
if this does not solve the problem, try after disabling anti virus.

Socket Hang Up when using https.request in node.js

When using https.request with node.js v04.7, I get the following error:
Error: socket hang up
at CleartextStream.<anonymous> (http.js:1272:45)
at CleartextStream.emit (events.js:61:17)
at Array.<anonymous> (tls.js:617:22)
at EventEmitter._tickCallback (node.js:126:26)
Simplified code that will generate the error:
var https = require('https')
, fs = require('fs')
var options = {
host: 'localhost'
, port: 8000
, key: fs.readFileSync('../../test-key.pem')
, cert: fs.readFileSync('../../test-cert.pem')
}
// Set up server and start listening
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end('success')
}).listen(options.port, options.host)
// Wait a second to let the server start up
setTimeout(function() {
var clientRequest = https.request(options, function(res) {
res.on('data', function (chunk) {
console.log('Called')
})
})
clientRequest.write('')
clientRequest.end()
}, 1000)
I get the error even with the server and client running on different node instances and have tested with port 8000, 3000, and 443 and with and without the SSL certificates. I do have libssl and libssl-dev on my Ubuntu machine.
Any ideas on what could be the cause?
In
https.createServer(function (req, res) {
you are missing options when you create the server, should be:
https.createServer(options, function (req, res) {
with your key and cert inside
I had a very similar problem where the response's end event never fired.
Adding this line fixed the problem:
// Hack to emit end on close because of a core bug that never fires end
response.on('close', function () {response.emit('end')});
I found an example of this in the request library mentioned in the previous answer.
Short answer: Use the the latest source code instead of the one you have. Store it where you will and then require it, you are good to go.
In the request 1.2.0 source code, main.js line 76, I see
http.createClient(options.uri.port, options.uri.hostname, options.uri.protocol === 'https:');
Looking at the http.js source code, I see
exports.createClient = function(port, host) {
var c = new Client();
c.port = port;
c.host = host;
return c;
};
It is requesting with 3 params but the actual function only has 2. The functionality is replaced with a separate module for https.
Looking at the latest main.js source code, I see dramatic changes. The most important is the addition of require('https').
It appears that request has been fixed but never re-released. Fortunately, the fix seems to work if you just copy manually from the raw view of the latest main.js source code and use it instead.
I had a similar problem and i think i got a fix. but then I have another socket problem.
See my solution here: http://groups.google.com/group/nodejs/browse_thread/thread/9189df2597aa199e/b83b16c08a051706?lnk=gst&q=hang+up#b83b16c08a051706
key point: use 0.4.8, http.request instead of http.createClient.
However, the new problem is, if I let the program running for long time, (I actually left the program running but no activity during weekend), then I will get socket hang up error when I send a request to http Server. (not even reach the http.request). I don't know if it is because of my code, or it is different problem with http Server