I am making a POST request to a webservice. The code for POST request is kept in a separate function.The function call from my intent function to the external function is asynchronous.So i am using Promises to achieve synchronicity.The problem here is that when i am importing request-promise-native inside my inline editor it's throwing error as TypeError: Cannot read property 'prototype' of undefined.
But when i tried it in my local workstation which has node js version 9.11.1 it worked fine.The Node JS version in DialogFlow is >=6.0.Is there any other dependency has to be added to it?
Can anyone please explain why this happens?
UPDATE:
I changed the node engine to 6.14.3 and the dependency for the module'request-promise-native' in package.json as "request-promise-native":"v1.0.5".But still no luck.The below is my code:
var doco;
var rp = require('request-promise-native');
var myJSONObject = {
"inputs" : [ {
"name" : "<name>",
"value" : <value>
} ]
};
var orchName = 'TEST05';
postData = JSON.stringify(myJSONObject);
return networkCall(postData,orchName).then((response)=>{
console.log('response is'+response)
console.log("+++++++++++++=DOCO=+++++++++ "+response);
doco = doco1;
//agent.add(`Order number is ${doco1}`);
}).catch((response) => {
console.log(`ERROR: `+response);
});
console.log('doco'+doco);
function networkCall(postData, orchName) {
return new Promise((resolve,reject) =>{
var options = {
method: 'post',
uri: '<URL>',
body: myJSONObject,
auth: {
'user': 'usr',
'pass': 'pwd'
},
json: true
};
return rp( options )
.then( body => {
// var test = JSON.stringify(body)
var doco =body.ServiceRequest1.subforms.z_DOCO_137.value;
console.log('DOCO '+doco);
resolve( doco );
})
.catch( err => {
console.log('FAILED'+err);
reject( err );
});
});
}
The error is thrown once i deploy the code in inline editor.The error is:
The deployment of your Cloud Function failed:
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: TypeError: Cannot read property 'prototype' of undefined
at module.exports (/user_code/node_modules/request-promise-native/node_modules/request-promise-core/configure/request2.js:34:47)
at Object.<anonymous> (/user_code/node_modules/request-promise-native/lib/rp.js:15:1)
at Module._compile (module.js:577:32)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/user_code/index.js:17:23)
The request-promise-native package requires the request package as a co-dependency. So you need to explicitly add this to the package.json tab in the Dialogflow editor.
Here is the package.json that works for me:
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "~6.0"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"actions-on-google": "2.0.0-alpha.4",
"firebase-admin": "^4.2.1",
"firebase-functions": "^0.5.7",
"dialogflow": "^0.1.0",
"dialogflow-fulfillment": "0.3.0-beta.3",
"request-promise-native": "^1.0",
"request": "^2.87"
}
}
Don't forget that, in addition to having the correct package, you will need to upgrade the project to a paid account. The free Firebase "Spark" plan does not allow network access outside of Google's network. You can upgrade to the "Blaze" plan which is pay-as-you-go, but does have a free tier which is sufficient for most development and testing purposes.
Related
I am trying to create a cli tool to make a todo list. For some reason I can't figure out I'm unable to use either require or import when trying to import the Chalk package for highlighting terminal outputs
here is what I have for my index.js file
#! /usr/bin/env node
const { program } = require("commander");
const list = require("./commands/list.js");
program.command("list").description("List all the TODO tasks").action(list);
program.parse();
Here is my list.js file
#! /usr/bin/env node
const conf = new (require("conf"))();
const chalk = require("chalk");
function list() {
const todoList = conf.get("todo-list");
if (todoList && todoList.length) {
console.log(
chalk.blue.bold(
"Tasks in green are done. Tasks in yellow are still not done."
)
);
todoList.forEach((task, index) => {
if (task.done) {
console.log(chalk.greenBright(`${index}. ${task.text}`));
} else {
console.log(chalk.yellowBright(`${index}. ${task.text}`));
}
});
} else {
console.log(chalk.red.bold("You don't have any tasks yet."));
}
}
module.exports = list;
and my package.json file
{
"name": "near-clear-state",
"version": "1.0.0",
"description": "Tool to let NEAR users clear the state of their account ",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "commonjs",
"author": "Dorian",
"license": "ISC",
"dependencies": {
"chalk": "^5.0.0",
"commander": "^8.3.0",
"conf": "^10.1.1",
"near-api-js": "^0.44.2"
},
"bin": {
"near-clear-state": "./index.js"
}
}
when I try running anything from this cli tool I'm making I get this error if I use require
➜ near-clear-state near-clear-state --help
/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:4
const chalk = require("chalk");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/node_modules/chalk/source/index.js from /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js not supported.
Instead change the require of index.js in /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:4:15)
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/index.js:3:14) {
code: 'ERR_REQUIRE_ESM'
}
Or this error when i use import
/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:3
import { Chalk } from "chalk";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1026:15)
at Module._compile (node:internal/modules/cjs/loader:1061:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/index.js:3:14)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
Node.js v17.4.0
Please help me
Use the import syntax, and add "type": "module" into your package.json to allow for ES6 imports.
I try to learn GraphQL. I wanted to try out the code that is in the Getting Started With GraphQL.js section in the graphql.org. I created a server.js file like this page says: https://graphql.org/graphql-js/
I followed instructions like:
npm init
npm install graphql --save
The package.json file looks like this:
{
"name": "graphql",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"graphql": "^16.0.1"
}
}
The server.js file I created looks exactly like the one from the page (it was copied):
var { graphql, buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Query {
hello: String
}
`);
// The root provides a resolver function for each API endpoint
var root = {
hello: () => {
return 'Hello world!';
},
};
// Run the GraphQL query '{ hello }' and print out the response
graphql(schema, '{ hello }', root).then((response) => {
console.log(response);
});
But after using the node server.js command (as written on the page) in the terminal, I get this error:
node_modules\graphql\type\schema.js:35
throw new Error(
^
Error: Expected undefined to be a GraphQL schema.
at assertSchema (F:\GraphQL\node_modules\graphql\type\schema.js:35:11)
at validateSchema (F:\GraphQL\node_modules\graphql\type\validate.js:34:28)
at graphqlImpl (F:\GraphQL\node_modules\graphql\graphql.js:52:64)
at F:\GraphQL\node_modules\graphql\graphql.js:21:43
at new Promise (<anonymous>)
at graphql (F:\GraphQL\node_modules\graphql\graphql.js:21:10)
at Object.<anonymous> (F:\GraphQL\server.js:18:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
Does anyone know what the problem is? Maybe I am missing some package? Or the code given on the page is wrong? Please help me, thank you in advance for any answer.
Goal
I want to get rid of some folders before the electron-forge's packaging step, because the option ignore.roge.config in package.json does not get rid of all the intermediate folders that I specify to ignore for some packages. Those intermediate folders are usually generated during a native build process during packaging.
Problem
But adding hooks field with the documented events don't seem to work, e.g.,
having a package.json field like this seems to add nothing to the equation, i.e., I don't see the expected console log.
"config": {
"forge": {
"packagerConfig": {
"icon": "src/images/myapp",
"ignore": [
"/.gitignore",
"/.vscode",
"/yarn.lock",
"/node_modules/mydep/build/",
"/node_modules/mydep/prebuilds/linux*"
]
},
"hooks": {
"prePackage": "async () => {\"console.log("this is prepackage step.");\"} "
},
"makers": [
{
"name": "#electron-forge/maker-zip",
"platforms": [
"darwin",
"win32"
]
}
]
}
},
Referring to a related elctron-forge github issue, I've also tried to feed a JS source file to hooks
"hooks": "require:./hooks.js",
where the hooks script looks like
{
prePackage: async () => {
console.log('this is prepackage step.');
}
}
This didn't work either.
Worse, I can't even specify multiple hooks this way:
{
generateAssets: async () => {
console.log('We should generate some assets here');
},
prePackage: async (forgeConfig, options) => {
console.error('lbn: prePackage');
}
}
The above code gives me the following error when running yarn make:
An unhandled error has occurred inside Forge:
Unexpected token ':'
/path/to/myapp/hooks.js:5
prePackage: async (forgeConfig, options) => {
^
SyntaxError: Unexpected token ':'
at wrapSafe (internal/modules/cjs/loader.js:1116:16)
at Module._compile (internal/modules/cjs/loader.js:1164:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
at Module.load (internal/modules/cjs/loader.js:1049:32)
at Function.Module._load (internal/modules/cjs/loader.js:937:14)
at Module.require (internal/modules/cjs/loader.js:1089:19)
at require (internal/modules/cjs/helpers.js:73:18)
at renderConfigTemplate (/path/to/myapp/node_modules/#electron-forge/core/src/util/forge-config.ts:100:20)
at _default (/path/to/myapp/node_modules/#electron-forge/core/src/util/forge-config.ts:145:3)
at /path/to/myapp/node_modules/#electron-forge/core/src/api/make.ts:96:19
error Command failed with exit code 1.
Question
What is the right way to specify hooks?
Solved it myself.
We should place the hooks as a normal global module
// ./hooks.js
const fs = require('fs');
const path = require('path');
module.exports = {
postPackage: async (forgeConfig, options) => {
console.warn('\n\npostPackage: exclude files ...\n\n');
}
}; // module.exports = {
Then refer to it in package.json
"hooks": "require:./hooks.js",
I'm trying to create VS Code extension. It works when fine when I develop, however when I create the package and install it to VS Code it is failing with following error:
ERR Cannot find module 'request': Error: Cannot find module 'request'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:602:15)
at Function.Module._load (internal/modules/cjs/loader.js:528:25)
at Function.t._load (c:\Users\USER\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:729:537)
at Function.t.getExtensionPathIndex.then.a._load (c:\Users\USER\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:691:639)
at Function.t.getExtensionPathIndex.then.r._load (c:\Users\USER\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:655:197)
at Module.require (internal/modules/cjs/loader.js:658:17)
at n (c:\Users\USER\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\loader.js:15:874)
at openBambooPlanUrlInBrowser.GIT.getGitBranchFromFileName (C:\Users\USER\.vscode\extensions\dUSER.markdown-table-of-contents-0.0.1\out\extension.js:397:41)
at getGitBranchFromFileName.exec (C:\Users\USER\.vscode\extensions\dUSER.markdown-table-of-contents-0.0.1\out\extension.js:383:17)
at ChildProcess.exithandler (child_process.js:294:7)
at ChildProcess.emit (events.js:182:13)
at maybeClose (internal/child_process.js:961:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:248:5)
my code:
async openBambooPlanUrlInBrowser(fileName: string) {
new GIT().getGitBranchFromFileName(fileName, (branch: string) => {
var config: any = vscode.workspace.getConfiguration('markdown-table-of-contents').get('bitbucketRepositories');
for (var setting of config) {
if (fileName.toLowerCase().startsWith(setting.folder.toLowerCase())) {
branch = branch.replace('/', '-');
let bambooHost = vscode.workspace.getConfiguration('markdown-table-of-contents').get('atlassianBambooHost');
const request = require('request');
request(
{
url: `${bambooHost}/rest/api/latest/plan/${setting.bambooPlanKey}/branch/${branch}.json`,
headers: {
"Authorization": 'Basic ' + vscode.workspace.getConfiguration('markdown-table-of-contents').get('atlassianAuthHash')
}
},
(error: string, response: string, body: string) => {
let planKey = JSON.parse(body).key;
vscode.env.openExternal(vscode.Uri.parse(`${bambooHost}/browse/${planKey}`));
}
);
}
}
});
}
dependencies from package.json
"dependencies": {
"child_process": "^1.0.2",
"clipboardy": "^1.2.3",
"fs": "0.0.1-security",
"iconv-lite": "^0.4.24",
"path": "^0.12.7",
"request": "^2.88.0",
"util": "^0.11.1",
"xml2js": "^0.4.19",
"xmldom": "^0.1.27"
}
root folder:
.gitignore
.vscode
.vscodeignore
depl.bat
markdown-table-of-contents-0.0.1.vsix
node_modules
out
package-lock.json
package.json
src
tsconfig.json
tslint.json
For me the solution was to run npm install <package_name> (notice no "-g") from the extension's code root folder. Vscode puts the extension in its [extension folder][1], navigate there to do npm install.
Example: for linux/mac
cd ~/.vscode/extensions
cd your.extension
npm install
This automatically added it to the devDependencies as well, and the extension worked perfectly from there on.
The Intern 4 Dojo loader cannot find the Dojo library in the ArcGIS JavaScript API. Does anyone know how to make the latest version of Intern work with Dojo and the ArcGIS JavaScript API?
The old fix no longer works. Intern says:
PS C:\UniServerZ\www\HelloIntern2> .\node_modules\.bin\intern
Config has unknown option "useLoader"
(????)?????
ReferenceError: define is not defined
at Object.<anonymous> <tests\unit\ViewByAttributeTest.js:1:63>
at Module._compile <module.js:652:30>
at Object.Module._extensions..js <module.js:663:10>
at Module.load <module.js:565:32>
at tryModuleLoad <module.js:505:12>
at Function.Module._load <module.js:497:3>
at Module.require <module.js:596:17>
at require <internal\module.js:11:18>
at Node.loadScript <src\lib\executors\Node.ts:260:5>
at Node._loader <src\loaders\default.ts:10:16>
Furthermore, given the intern.json file at the end of this post, intern says:
PS C:\UniServerZ\www\HelloIntern2> .\node_modules\.bin\intern
(????)?????
Error: Cannot find module 'node_modules/dojo/dojo.js' from 'C:\UniServerZ\www\He
lloIntern2'
at Function.module.exports [as sync] <node_modules\resolve\lib\sync.js:40:15>
at Node.loadScript <src\lib\executors\Node.ts:264:13>
at <src\loaders\dojo.ts:17:15>
at Node.Executor.registerLoader <src\lib\executors\Executor.ts:468:37>
at Object.<anonymous> <src\loaders\dojo.ts:6:7>
at Module._compile <module.js:652:30>
at Object.Module._extensions..js <module.js:663:10>
at Module.load <module.js:565:32>
at tryModuleLoad <module.js:505:12>
at Function.Module._load <module.js:497:3>
intern.json:
{
"loader" : {
"script" : "dojo",
"options" : {
"packages" : [{
"name" : "zian",
"location" : "/zian"
}, {
"name" : "dgrid",
"location" : "http://js.arcgis.com/4.6/dgrid"
}, {
"name" : "dijit",
"location" : "http://js.arcgis.com/4.6/dijit"
}, {
"name" : "esri",
"location" : "http://js.arcgis.com/4.6/esri"
}, {
"name" : "dojo",
"location" : "http://js.arcgis.com/4.6/dojo"
}, {
"name" : "dojox",
"location" : "http://js.arcgis.com/4.6/dojox"
}, {
"name" : "moment",
"location" : "http://js.arcgis.com/4.6/moment"
}
]
}
},
"filterErrorStack" : false,
"suites" : ["tests/unit/*.js"],
"environments" : ["chrome", "node"]
}
Finally, for the sake of completeness, here is the full directory structure:
app has: calc.js and index.js
js has: starter.js
node_module has: tons and tons of folder...
test has: unit has: ViewByAttributeTest.js
zian has: ViewByAttribute.js
root of the folder has the above folders and: index.html, index.js, intern.json, package.json, and package-lock.json
package.json:
{
"name": "helloworldcdnapi",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"author": "Zian Choy",
"license": "ISC",
"dependencies": {
"intern": "^4.0.0-rc.1"
}
}
ViewByAttributeTest.js
define([
'require'
], function (require) {
var registerSuite = intern.getInterface('object').registerSuite;
var assert = intern.getPlugin('chai').assert;
registerSuite('ViewByAttribute', {
'default data': function () {
assert.strictEqual(1, 1, '1 is 1.');
}
});
});
Incidentally, if you read this far, I hope you can appreciate the humor in computers failing to recognize that 1 is equal to 1.
You'll need to do several things to get this to work. First, you'll need to add a custom loader to load dojo, then you'll need to change your script to reference that new dojo loader file in intern.json. That file will look something like:
intern.registerLoader(function(options) {
// do checks here
return intern.loadScript(<location of your dojo file in arcgis js api>)
.then(function() {
//do stuff here
})
});
There is a document to explain the process to setting intern 4 on WebAppbuilder for ArcGIS. WAB use ArcGIS API for Javascript.
Best Practices for Unit Test on WAB