How to solve this Error: Cannot find module 'ibm-watson' - node.js

I have installed ibm-watson using "npm install ibm-watson" command
I can see the folder and its file in the node_modules folder, but still showing this error.
Node version - v10.15.3
const watson = require('ibm-watson');
const { IamAuthenticator } = require('ibm-watson/auth');
const { BasicAuthenticator } = require('ibm-watson/auth');
// to get an IAM Access Token
const authorization = new watson.AuthorizationV1({
authenticator: new IamAuthenticator({ apikey: 'fakekey-1234' }),
});
authorization.getToken(function (err, token) {
if (!token) {
console.log('error: ', err);
} else {
// Use your token here
}
});
Other modules are importing fine, Only this module not importing.
internal/modules/cjs/loader.js:584
throw err;
^
Error: Cannot find module 'ibm-watson'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
at Function.Module._load (internal/modules/cjs/loader.js:508:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous>

I've just faced this issue. I did not install the correct version of the package. Please check the apidocs for Node to see the correct version of IBM Watson npm package that you need. for me I needed 5.6.0.
You can install it with the following command:
npm install ibm-watson#^5.6.0

As you are getting a token, I am going to guess that you are using Speech To Text. As the comments have suggested the failing line is const watson = require('ibm-watson'); because it isn't exported. Instead you would use, as per the API documentation - https://cloud.ibm.com/apidocs/speech-to-text/speech-to-text?code=node#authentication:
const SpeechToTextV1 = require('ibm-watson/speech-to-text/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const { IamTokenManager } = require('ibm-watson/auth');
If it's not STT that you are using then the other services work the same way when requiring ibm-watson. Links to the API Docs can be found here - https://cloud.ibm.com/apidocs

I faced the same problem. 
After reading the code, I understood.
There is only sdk.ts file, not index.ts file.
https://github.com/watson-developer-cloud/node-sdk
// const watson = require('ibm-watson');
const watson = require('ibm-watson/sdk');
But I still got the error.
Eventually it worked if I wrote the following
import AuthorizationV1 from 'ibm-watson/authorization/v1'
import { IamAuthenticator } from 'ibm-watson/auth'
const apikey = '********'
const authorization = new AuthorizationV1({
url: 'https://iam.cloud.ibm.com/identity/token',
authenticator: new IamAuthenticator({ apikey }),
})
authorization.getToken(function (err, token) {
if (!token) {
console.log('error: ', err);
} else {
// Use your token here
}
});
But there is a CORS problem. I don't know any more.
The answer was written here. I need to do it on the server side
https://github.com/watson-developer-cloud/node-sdk/issues/884#issuecomment-515050023

Related

Module not found: Can't resolve 'ipfs-http-client' in 'D:\Pro\src\components'

I am trying to send files to ipfs using a website in node-js. I am using the ipfs-http-client module. When i try to access the module using require I keep getting this error :
Module not found: Can't resolve 'ipfs-http-client' in 'D:\Pro\src\components' in the command prompt.
This the error message in the website :
Failed to compile
./src/components/App.js
Module not found: Can't resolve 'ipfs-http-client' in 'D:\Pro\src\components'
This error occurred during the build time and cannot be dismissed.
I installed the module using the command specified in the official docs -
"npm install --save ipfs-http-client" . I can see the module in my dependencies but still getting this error.
I am a complete newbie to all this. A little help would be much appreciated. Thanks in advance.
This is how I am accessing the module :
***import React, { Component } from 'react';
import logo from '../logo.png';
import './App.css';
const ipfsClient = require('ipfs-http-client');
const projectId = '*****';
const projectSecret = '***';
const auth =
'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');
const ipfs = ipfsClient.create({
host: 'ipfs.infura.io',
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
},
});
class App extends Component {
constructor(props) {
super(props);
this.state={
buffer: null
};
}
captureFile=(event) => {
event.preventDefault()
const file = event.target.files[0]
const reader = new window.FileReader()
reader.readAsArrayBuffer(file)
reader.onloadend=() => {
this.setState({buffer: Buffer(reader.result) })
}
console.log(event.target.files)
}
onSubmit = (event) => {
event.preventDefault()
console.log("Submitting the form...")
ipfs.add(this.state.buffer, (error,result) => {
console.log('Ipfs result', result)
if(error){
console.error(error)
return
}
})
}***
Try using earlier version I have just tried it. Do the following :
npm uninstall --save ipfs-http-client
npm i --save ipfs-http-client#33.1.1
I do not know what the problem is with the updated version but this is a quick fix up for now. And will get your code running
Import it like this:
const ipfsClient = require('ipfs-http-client');
Then create the connection:
const ipfs = ipfsClient.create(https://ipfs.infura.io:5001);
To upload:
const uploadFile = await ipfs.add({ content: file });
Maybe you're missing the babel loaders I got this working using the following:
npm i ipfs-http-client#50.1.2 #babel/core --save
If you take a look at the package at the npm website, you'll see that the newer versions import the create-function as such:
import { create } from 'ipfs-http-client'
Using this, you can simply change your code to
import React, { Component } from 'react';
import logo from '../logo.png';
import './App.css';
import { create } from 'ipfs-http-client';
const projectId = '*****';
const projectSecret = '***';
const auth =
'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');
const ipfs = create({
host: 'ipfs.infura.io',
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
},
});
class App extends Component {
...
}

How do I Fix a Cannot find module '.functions/handleCommands.js' error?

Upon running my Bot to have it sign-on after installing a command and event handler I got the error
Error: Cannot find module '.functions/handleCommands.js'
Require stack:
C:\Users\levan\Desktop\Discordbot\Bot Templates\2 command handling\src\bot.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at C:\Users\levan\Desktop\Discordbot\Bot Templates\2 command handling\src\bot.js:14:9
at Object.<anonymous> (C:\Users\levan\Desktop\Discordbot\Bot Templates\2 command handling\src\bot.js:19:3)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12) { code:
'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\levan\\Desktop\\Discordbot\\Bot Templates\\2 command handling\\src\\bot.js'
After looking thru the folder functions and the handleCommands.js, I Still cannot figure out what I'm missing or what I might on messed up. I thought that maybe my module.exports was in the wrong place but moving things around did not solve the issue either.
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const clientId = 'redacted'; // your bots token
const guildId = 'redacted'; // the server id the bot will be on
module.exports = (clinet) => {
clinet.handleCommands = async (commandFolders, path) =>{
clinet.commandArray = [];
for(folder of commandFolders){
const commandFiles = fs.readdirSync(`${path}/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`../commands/${folder}/${file}`);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
client.commands.set(command.data.name, command);
clinet.commandArray.push(command.data.toJSON());
}
}
};
};
const rest = new REST({ version: '9' }).setToken(process.env.token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: clinet.commandArray },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
As the error was MODULE_NOT_FOUND I figured that maybe I didn't run all the installs I need to make my bot work. After running thru my npm lists the error persisted.
NPM's Installed
"npm init"
"npm install discord.js"
"npm install dotenv"
"npm install discord.js dotenv"
"npm install #discordjs/rest discord-api-types #discordjs/builders"
My goal is to be the Bot back online and to figure out how to troubleshoot this sort of error in case it comes up again. Any help you can give will be greatly appreciated.
'.functions/handleCommands.js' should have been './functions/handleCommands.js' Caffeine is not a substitute for sleep

Connection to oracle database via nodeJS

I'm trying to establish an Oracle connection using NodeJS but while trying to connect i am receiving below error.
Error: Error: DPI-1047: Cannot locate a 64-bit Oracle Client library: "The specified module could not be found". See https://oracle.github.io/odpi/doc/installation.html#windows for help
Node-oracledb installation instructions: https://oracle.github.io/node-oracledb/INSTALL.html
You must have 64-bit Oracle client libraries in your PATH environment variable.
If you do not have Oracle Database on this computer, then install the Instant Client Basic or Basic Light package from
http://www.oracle.com/technetwork/topics/winx64soft-089540.html
A Microsoft Visual Studio Redistributable suitable for your Oracle client library version must be available.
at OracleDb.getConnection (C:\NodeCon\node_modules\oracledb\lib\oracledb.js:270:10)
at C:\NodeCon\node_modules\oracledb\lib\util.js:180:16
at new Promise (<anonymous>)
at OracleDb.getConnection (C:\NodeCon\node_modules\oracledb\lib\util.js:168:14)
at C:\NodeCon\server.js:41:32
at Object.<anonymous> (C:\NodeCon\server.js:58:3)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14) {
errorNum: 0,
offset: 0
I've downloaded and installed 64 bit Oracle Client Library but still below error appears.
Using Visual Studio Code v.1.36 as my editor.
NodeJS code i'm using is as below :
let connection;
var oracledb = require('oracledb');
(async function(){
try{
connection = await oracledb.getConnection({
user: 'Username',
password: 'Password',
connectString: 'hostname:portname/servicename'
});
console.log("Successfully connected");
} catch(err){
console.log("NOT connected");
}finally{
if(connection){
try{
await connection.close();
}catch(err){
console.log("Errror");
}
}
}
})()
Any help will be much appreciated. Thanks.
This got resolved by following code:
oracledb.getConnection({
user: 'username',
password: 'Password',
connectString: 'hostname:portname/servicename'
},
function(err, connection) {
if (err) throw err;
connection.execute(
//Your database query here.
//below code if you want to fetch data from database and show it on terminal
function(err,results){
var metaData = {};
var rows = {};
console.log("error")
if (err){
throw err
}
metaData.name1 = results.metaData[0].name;
metaData.name2 = results.metaData[1].name;
rows.row1 = results.rows[0][0];
rows.row2 = results.rows[0][1];
rows.row3 = results.rows[0][2];
console.log(metaData.name1+" : "+rows.row1)
console.log(metaData.name2+" : "+rows.row2)
console.log("Successfully connected");
);
}
And if you're connecting via VPN make sure to connect to the server first then run above.

Firebase - TypeError: Path must be a string. Received undefined

I am just starting up with firebase.
i am not sure ins and out of the firebase and based on my vaguely understanding, I have configured my app this way.
In the main Index.js file, I am requiring
const path = require('path')
const firebaseConfig = require("./src/config/firebaseConfig.js")
const firebaseDb = require("./src/helperFunctions/firebase_db.js")
Here, firebaseConfig is the place where I am configuring my firebase
const firebaseConfigJSON = require("./functions-config.json")
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.cert(firebaseConfigJSON),
databaseURL: "https://functions-firebase-43a59.firebaseio.com"
})
const db = admin.firestore()
db.settings({ timestampsInSnapshots: true });
module.exports = {
db
}
and then using this imported Db in firebaseDb
//All the operations at firebase store would be done from here
const firebaseDb = require("./../config/firebaseConfig.js")
firebaseDb.db.collection('users').add({
name: "Rohit Bhatia",
age: "24"
})
.then((response) => {
console.log("this is response", response)
})
.catch((err) => {
console.log("This is error in firebase", err)
})
Since most of the code is singleton here, I was expecting everything to go smoothly until I received following error
This is error in firebase TypeError: Path must be a string. Received
undefined
at assertPath (path.js:28:11)
at Object.join (path.js:1236:7)
at getPath (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/dir-glob/index.js:6:41)
at globs.concat.map.x (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/dir-glob/index.js:47:59)
at Array.map ()
at module.exports.sync (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/dir-glob/index.js:47:33)
at globDirs (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/globby/index.js:58:9)
at getPattern (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/globby/index.js:61:64)
at globTasks.reduce (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/globby/index.js:107:19)
at Array.reduce ()
Can someone please help me in figuring out what could I be doing wrong? or perhaps did I actually got the firebase?
My initial goal was to create a collection in my firebase via my express app before putting data from api routes.
Try running:
npm install firebase-admin#6.4.0
Also you can do:
npm install
npm run build (inside functions folder.)
Then firebase deploy.
Fixed it for me.
We were able to revert the dir-glob to 2.0.0 by adding:
"dir-glob": "2.0.0",
"globby": "8.0.0",
In the package.json dependencies.
You can do this with:
npm install dir-glob#2.0.0 --save
npm install globby#8.0.0 --save
We then deleted the node_modules and run: npm install and deployed to Firebase
Future googler's
Make sure in your firebase.json file you have the correct source path:
{
"functions": {
"predeploy": "npm run build",
"source": "."
}
}

Connect Node.js BOT to MS Azure SQL database

I have a working MS Teams bot written in Node.js. The bot asks a series of questions and currently displays the responses at the end by accessing the session variables. All well and good.
Now I am attempting to store the session variables in a MS Azure SQL DB. The DB is correctly set up in Azure as I can access and write data to it in SSMS. But I believe I am probably connecting incorrectly to the DB in my bot code. The bot code I am using is pulled from:
connecting to SQL using Node.js
That code makes sense to me. But how do I use that code in my bot? Here is what I have attempted thus far...
Currently I am using the local memory MemoryBotStorage() and setting to that.
var inMemoryStorage = new builder.MemoryBotStorage();
.set('storage', inMemoryStorage)
In another Microsoft article dealing with the Azure Cosmos DB it states "4.Specify that you want to use your custom database instead of the in-memory storage." So from this I deduce that I hafta add my instantiated sql db to the .set('storage', DB Goes Here) but my attempts have failed and I am not sure if I am even correct?
So my question is how do I correctly access the Azure sql server DB form my bot code - and is the link I provided even the correct way?
Thank you
Note - This code sample worked for me - I was able to connect and query my Azure DB - but it is only DB code and does not take into consideration bot code.
EDIT - Code:
const builder = require('botbuilder');
const builderTeams = require('botbuilder-teams');
const restify = require('restify');
const connector = new builderTeams.TeamsChatConnector(
{
appId: "My app ID,
appPassword: "My App PW",
}
);
var inMemoryStorage = new builder.MemoryBotStorage();
const bot = new builder.UniversalBot(connector, [
function (session) {
session.send("Welcome.");
builder.Prompts.text(session, "Question1?");
},
function (session, results) {
session.dialogData.question1 = results.response;
builder.Prompts.text(session, "Question2?");
},
function (session, results) {
session.dialogData.Question2 = results.response;
builder.Prompts.text(session, "Question3?");
},
function (session, results) {
session.dialogData.Question3 = results.response;
// Begin DB
var Connection = require('tedious').Connection;
var config = {
userName: 'myusername',
password: 'mypw',
server: 'myserver.database.windows.net',
// If you are on Azure SQL Database, you need these next options.
options: { encrypt: true, database: 'mydb' }
};
var connection = new Connection(config);
connection.on('connect', function (err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement1();
});
var Request = require('tedious').Request
var TYPES = require('tedious').TYPES;
function executeStatement1() {
request = new Request("INSERT my (Username, Question1, Question2, Question3, StatusDate) VALUES (#Username, #Question1, #Question2, #Question3, CURRENT_TIMESTAMP);", function (err) {
if (err) {
console.log(err);
}
});
request.addParameter('Username', TYPES.NVarChar, session.userData.userName);
request.addParameter('Question1', TYPES.NVarChar, session.dialogData.Question1);
request.addParameter('Question2', TYPES.NVarChar, session.dialogData.Question2);
request.addParameter('Question3', TYPES.NVarChar, session.dialogData.Question3);
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log("ID of inserted item is " + column.value);
}
});
});
connection.execSql(request);
// End DB
// Process request and display details
session.endDialog();
}
]).set('storage', inMemoryStorage)
const server = restify.createServer();
server.post('api/messages', connector.listen());
server.listen(portnumber)
Error when running with npm start:
npm start
> simplebot#1.0.0 start C:\Developer\dailyStatus
> node index.js
C:\Developer\dailyStatus\index.js:81
]).set('storage', inMemoryStorage)
^
SyntaxError: Unexpected token ]
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
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 Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! simplebot#1.0.0 start: `node index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the simplebot#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely...
npm ERR! A complete log of this run can be found in:
npm ERR! C: etc.
FINAL
I was able to able to get this working with this tutorial. Thanks also to Marc LeFleur.
You have several typos. For example, you're missing the closing " on appId:
const connector = new builderTeams.TeamsChatConnector(
{
appId: "My app ID",
appPassword: "My App PW",
}
);
You also can't declare the function executeStatement1() {...} function within the your IDialogWaterfallStep function. This needs to live outside the constructor and called from the IDialogWaterfallStep.

Resources