How to remove TypeError: "x" is not a function? - node.js

I am trying to learn how to make a discord bot and pull data from this API called Ergast (http://ergast.com/mrd). I found this npm (https://github.com/estevE11/f1-stats) which uses NodeJS implementation to get a historical record of F1 data from Ergast API. Sorry for the bad wording I am still trying to learn the lingo.
I followed what was stated in the npm documentation for installing it and tried using the example to get data from the API. However when I run the code in index.js I get the error "TypeError: "x" is not a function". When I go into the node_modules "f1-stats" folder and run the code from main.js I do get the correct result.
index.js:
const client = new Discord.Client(); //This will be our client
const { prefix, token } = require('./config.json');//const PREFIX = '!';
const f1s = require('f1-stats');
//module.exports.f1s = f1s; //Still causes the TypeError
f1s("2008 drivers", (res) => {
console.log(res);
});
The error message I get in index.js:
f1s("2008 drivers", (res) => {
^
TypeError: f1s is not a function
at Object.<anonymous> (C:\Users\RyanPC\Documents\DiscordBot\index.js:8:1)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
node_modules/f1-stats/main.js:
const f1s = require("./f1-stats"); // "./" is used because module is located in the same folder as the Node.js file
f1s("2008 drivers", (res) => {
console.log(res);
});
when I run it in node_modules/f1-stats/main.js:
{ MRData:
{ xmlns: 'http://ergast.com/mrd/1.4',
series: 'f1',
url: 'http://ergast.com/api/f1/2008/drivers.json',
limit: '30',
offset: '0',
total: '22',
DriverTable: { season: '2008', Drivers: [Array] } } }

Because f1-stats doesn't export anything so when you import it. It is empty. The correct file you need to import is f1-stats/f1-stats.
const f1s = require('f1-stats/f1-stats');

try importing f1s properly , you are getting error because you have not imported the function properly , in other words...check what is being exported from what are you trying to import....hope it solves the problem.

Related

Error in VSCode, while i try create a spotify discord bot: [ SyntaxError: Cannot use import statement outside a module ] with node.js [duplicate]

This question already has answers here:
SyntaxError: Cannot use import statement outside a module
(34 answers)
Closed 23 days ago.
I can't execute and debug my discord bot, having an error in debugging console.
This is my code in the bot:
const discord = require('discord.js');
const client = new discord.Client({
ws: { intents: discord.Intents.ALL },
});
import spotify from 'spotify-web-api-js';
const spotifyAPI = new spotify();
import { MessageEmbed } from 'discord.js';
//Spotify Credentials
spotifyAPI.setAccessToken('HIDDEN');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', message => {
if (message.content.startsWith('!play')) {
let songName = message.content.split(" ").slice(1).join(" ");
spotifyAPI.searchTracks(songName)
.then(function(data) {
let song = data.tracks.items[0];
let songName =song.name;
let songUrl =song.preview_url;
let songAuthor =song.artists[0].name;
let songEmbed = new MessageEmbed()
.setTitle(`Playing ${songName}`)
.setURL(songUrl)
.setAuthor(songAuthor)
.setColor('#0099ff')
message.channel.send(songEmbed);
}, function(err) {
console.error(err);
message.channel.send("Sorry, I couldn't find the song you requested. Please try again with a different name or check your internet connection.");
});
}
});
client.login('HIDDEN');
And i have this error in my debugging console:
Uncaught SyntaxError C:\Users\MY_USERNAME\Proyectos de VS Code\spoticord\spoticord.js:6
import spotify from 'spotify-web-api-js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at compileFunction (vm:360:18)
at wrapSafe (internal/modules/cjs/loader:1088:15)
at Module._compile (internal/modules/cjs/loader:1123:27)
at Module._extensions..js (internal/modules/cjs/loader:1213:10)
at Module.load (internal/modules/cjs/loader:1037:32)
at Module._load (internal/modules/cjs/loader:878:12)
at executeUserEntryPoint (internal/modules/run_main:81:12)
at <anonymous> (internal/main/run_main_module:23:47)
Process exited with code 1
I tried update discord.js, spotify-web-api-js, reinstall both modules.
But gives another errors like:
TypeError: Cannot read properties of undefined (reading 'ALL')
SyntaxError: Identifier 'Discord' has already been declared
Valid intents must be provided for the Client.
Your package's settings are for "CommonJS", when import is allowed for "module" types.
// at line 6
import spotify from 'spotify-web-api-js'
// at line 9
// this must be replaced also, like at line 6
import { MessageEmbed } from 'discord.js';
There are two correct solutions.
Set "type" as "module" in "package.json" and use import <name> from <module> instead of const <name> = require("<module>")
Replace import spotify from 'spotify-web-api-js'; with const spotify = require("spotify-web-api-js"), because "CommonJS" doesn't support "import"

Cannot find module 'posts.graphql' using loadSchema and GraphQLFileLoader from graphql-tools

I am trying to load schema from a specific folder.
I am trying to not using Apollo, a pretty good solution that I found is loadSchema from #graphql-tools/load.
const { loadSchema } = require('#graphql-tools/load');
const { GraphQLFileLoader } = require('#graphql-tools/graphql-file-loader');
async function getLoadedSchema() {
const schemas = await loadSchema('/absolute/path/*.graphql', {
loaders: [new GraphQLFileLoader()]
})
console.log('mySchema', schemas);
}
By launching the server, I get this error:
Running a GraphQL API server at http://localhost:4000/graphql
(node:30146) UnhandledPromiseRejectionWarning: Error: Cannot find module 'posts.graphql'
Require stack:
- /absolute/path/src/routes/users/create/noop.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)
at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (/Users/myUser/.asdf/installs/nodejs/12.22.1/.npm/lib/node_modules/ts-node/node_modules/#cspotcode/source-map-support/source-map-support.js:679:30)
at resolveFileName (/absolute/path/node_modules/resolve-from/index.js:29:39)
at resolveFrom (/absolute/path/node_modules/resolve-from/index.js:43:9)
at module.exports (/absolute/path/node_modules/resolve-from/index.js:46:47)
at resolveFilePath (/absolute/path/node_modules/#graphql-tools/import/index.js:395:20)
at visitFile (/absolute/path/node_modules/#graphql-tools/import/index.js:57:20)
at processImports (/absolute/path/node_modules/#graphql-tools/import/index.js:291:41)
at visitFile (/absolute/path/node_modules/#graphql-tools/import/index.js:66:82)
at Object.processImport (/absolute/path/node_modules/#graphql-tools/import/index.js:36:1
I don't really know where the comes from.
Do you have some ideas ?

How to suppress Jest Linter errors from import files?

So I'm trying to do some basic API testing with Jest by importing a function from handler.ts but Jest crawls through the handler ts imports and gives me linter errors for a file that handler importest from my libs folder when all I want to do is check if the result of that function equals what I want it to equal.
Here's my test file test/handler.test.ts:
import { getInbox } from './../handler'
import * as myMongo from '../../../libs/mongo';
import { Db } from 'mongodb';
const productionDbPromise: Promise<Db> = myMongo.getProductionDb();
test("Case page 1, limit 5", async ()=>{
const page = 1;
const limit = 5;
const event = {
queryStringParameters: {
page: page,
limit: limit
}
};
const productionDb = await productionDbPromise;
const seekerCollection = productionDb.collection('seekers');
const totalDocs = await seekerCollection.countDocuments({ lastMessageDate: { $ne: null } });
const code = 200;
const status = 'OK';
const res: any = await getInbox(event);
expect(res.code).toEqual(code);
expect(res.status).toEqual(status);
expect(res.json().totalDocs).toEqual(totalDocs);
expect(res.json().seekers.length).toEqual(limit);
});
And here's the error:
Test suite failed to run
TypeError: twilio is not a function
6 | export const client = twilio(accountSid, authToken);
7 | export const messagingServiceSid = process.env.TWILIO_SERVICE_ID;
> 8 |
| ^
at Object.<anonymous> (../../libs/twilio.ts:8:18)
at Object.<anonymous> (../../libs/message.ts:7:18)
at Object.<anonymous> (handler.ts:14:19)
at Object.<anonymous> (__test__/handler.test.ts:4:19)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 12.086 s
npm ERR! Test failed. See above for more details.
Any idea how to get it to ignore this? (which by the way the function I'm testing does not even use any exports from that libs file, and the twilio object is correctly imported on the first line of that file)
It's not Jest's responsibility to run a linter, also it doesn't crawl through any modules that weren't explicitly imported.
This is not linter but runtime error, and it cannot be suppressed or discarded. The problem is exactly what it says:
TypeError: twilio is not a function
Call stack gives a good idea where it comes from:
at Object.<anonymous> (../../libs/twilio.ts:8:18)
at Object.<anonymous> (../../libs/message.ts:7:18)
at Object.<anonymous> (handler.ts:14:19)
at Object.<anonymous> (__test__/handler.test.ts:4:19)
handler.ts depends on message.ts, and message.ts depends on twilio.ts, where the error happens. If twilio is not supposed to be available in tests, either it or one of these modules need to be mocked.

Why do I get a UserCodeSyntaxError when I have no syntax error in my code?

I'm currently creating a Dialogflow chatbot in nodejs and upon deploying my code I get an error message. I've attempted to uncomment most things out to just be left with the base functioning code and I am still unable to get it working. I'm not exactly sure what the issue is here
'use strict';
import {getAPIresponse} from "./api/index.js";
// const http = require('https');
// const respond = fulfillmentText => {
// return {
// statusCode: 200,
// body: JSON.stringify({
// fulfillmentText
// }),
// headers: {
// "Content-Type": "application/json"
// }
// }
//
// };
module.exports.dining = async (event,context) => {
const incoming= JSON.parse(event.body).queryResult;
console.log(`INCOMING: ${incoming.parameters.hall}`);
const {
displayName
} = incoming.intent;
console.log(displayName);
//const menu = getAPIresponse('https://esb.prod.uds.harvard.edu/api/dining/2.0/','events?locationId=36');
//console.log(menu);
// if(displayName === 'dining'){
// if(incoming.parameters.meal === 'breakfast'){
// //get's dining hall code to include in API request
// const hall = getCode(incoming.parameters.hall);
// //generate response from API based off of parameters passed by user
// const menu = getAPIresponse("https://esb.prod.uds.harvard.edu/api/dining/2.0/","events?locationId=${hall}", hall);
// console.log(menu);
// }
// if(incoming.parameters.meal === 'lunch'){
// //get's dining hall code to include in API request
// const hall = getCode(incoming.parameters.hall);
// //generate response from API based off of parameters passed by user
// const menu = getAPIresponse("https://esb.prod.uds.harvard.edu/api/dining/2.0","/events", hall);
// }
// if(incoming.parameters.meal === 'dinner'){
// //get's dining hall code to include in API request
// const hall = getCode(incoming.parameters.hall);
// //generate response from API based off of parameters passed by user
// const menu = getAPIresponse("https://esb.prod.uds.harvard.edu/api/dining/2.0","/events", hall);
// }
// }
};
Almost everything is commented out and I still get the error message that reads
2019-07-02 16:31:33.351 (-04:00) undefined ERROR Uncaught Exception {
"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Unexpected tok
en {","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Unexpected token {"," at
_loadUserApp (/var/runtime/UserFunction.js:98:13)"," at Object.module.exports.loa
d (/var/runtime/UserFunction.js:140:17)"," at Object.<anonymous> (/var/runtime/ind
ex.js:36:30)"," at Module._compile (internal/modules/cjs/loader.js:701:30)"," a
t Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)"," at Modu
le.load (internal/modules/cjs/loader.js:600:32)"," at tryModuleLoad (internal/modu
les/cjs/loader.js:539:12)"," at Function.Module._load (internal/modules/cjs/loader
.js:531:3)"," at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)",
" at startup (internal/bootstrap/node.js:283:19)"]}
Worked for me: Updating Node.js version of lambda
I got this error because lambda was defined to execute with Node.js 12.x, when I changed it to Node.js 14.x (as on my local machine) it worked
If it works - and you're generally using the serverless package to automate the deployment of your lambda - don't forget to update your serverless.yml file accordingly
AWS Lambda does not support the ES6 import specifier as you've written here
import {getAPIresponse} from "./api/index.js";
because the ES6 import syntax isn't yet supported by default in Node.js (note: my lambda runtime was set to Node.js 10.x).
Illustration:
I was having this issue as well when importing a library at the top of my lambda distribution's index.js file.
The stacktrace Uncaught Exception { "errorType":"Runtime.UserCodeSyntaxError", ... unexpected token import found ... blabla... } ... was thrown in my lambda function when I used the import syntax:
import awsServerlessExpress from 'aws-serverless-express';
exports.handler = (event, context) => {
console.log('hello world!')
};
But not in this version below when I just used the standard module require syntax.
const awsServerlessExpress = require('aws-serverless-express');
exports.handler = (event, context) => {
console.log('hello world!')
};
For me, it was the import syntax that was causing the SyntaxError exceptions, but do take note that, for you, any JavaScript syntax not supported by your current Node.js runtime will throw this exception.
A couple of solutions:
Change all import statements to standard module require statements and keep using whatever default JavaScript flavour is supported by your configured Node.js runtime.
Use a transpiler like Babel w/ Webpack to transpile your ES6 JavaScript before deploying to the cloud.
Use the quick solution nicely described by Yitzchak below :) Just bump the NodeJS version on your Lambda Dashboard.
In my case, I pasted code from another lambda which had node version 14.
But my current lambda node version was 12.
The code I pasted was using optional chaining(?.) in one line. Removed it, deployed code and it worked fine.
If you are using TypeScript and encounter this error make sure the target you set in tsconfig.json matches your targeted nodejs version. For a list of recommended settings visit Node Target Mapping
For example I was targeting node.js 12 and using ES2020. Changing this to ES2019 fixed my issue.
Sometimes in lambda, when we click on Deploy all the changes are not deployed. Refresh the page and check for syntax errors.
or at least that's what was the problem in my case.
In my case I changed the tsconfig.json module setting:
"module": "es2015"
to
"module": "CommonJS",
ref: https://www.typescriptlang.org/tsconfig#module

Type Error: Cannot read property 'hasListCollectionsCommand' of null

I'm trying to get all collection names in mongodb (v4.0.2) and using mongodb#3.1.10 nodejs driver. From the docs, I can see that listCollections might work, but running the following:
const Db = require('mongodb').Db
const Server = require('mongodb').Server
const db = new Db(dbName, new Server(host, port, options), {})
db.listCollections().toArray((error, collectionNames) => {
console.error(error)
console.log(JSON.stringify(collectionNames))
})
… leads to this error:
if (this.serverConfig.capabilities().hasListCollectionsCommand) {
TypeError: Cannot read property 'hasListCollectionsCommand' of null
at Db.listCollections ({path}/node_modules/mongodb/lib/db.js:493:39)
at db.createCollection ({path}/sampleMongoDB.js:19:8)
at err ({path}/node_modules/mongodb/lib/utils.js:415:14)
at executeCallback ({path}/node_modules/mongodb/lib/utils.js:404:25)
at executeOperation ({path}/node_modules/mongodb/lib/utils.js:422:7)
at Db. ({path}/node_modules/mongodb/lib/db.js:431:12)
at Db.deprecated [as createCollection] ({path}/node_modules/mongodb /lib/utils.js:661:17)
at Object.< anonymous > ({path}/sampleMongoDB.js:18:6)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
My questions are:
Is there a docs site for MongoDB NodeJs drivers where we can refer examples from?
If not, what's the correct way to query?
I was able to work it out. The MongoClient's instance returns a db instance, which inturn helps run mongodb.Db methods.
Here's a sample code that worked (Ref. to MongoDB guides)
const options = {
useNewUrlParser: true, // Add this, if you wish to avoid {https://stackoverflow.com/questions/50448272/avoid-current-url-string-parser-is-deprecated-warning-by-setting-usenewurlpars} issue
}
const client = new MongoClient(connectionUri, options)
return client.connect().then(() => {
const db = client.db(dbName)
return db.listCollections()
.toArray()
.then((collections) => {
// Collections array
})
})
#Community mods - if required, kindly close this question.

Resources