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

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"

Related

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 ?

Why I can not use " import { createSlice, configureStore } from '#reduxjs/toolkit' " in Node.js

guys
I am learning redux, and try to run a very simple example code in node.js environment. I got the following error when I try to use :
import { createSlice, configureStore } from '#reduxjs/toolkit' .
The errors is:
import { createSlice, configureStore } from '#reduxjs/toolkit'
^^^^^^^^^^^
SyntaxError: Named export 'createSlice' not found. The requested module '#reduxjs/toolkit' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from '#reduxjs/toolkit';
const { createSlice, configureStore } = pkg;
at ModuleJob._instantiate (internal/modules/esm/module_job.js:120:21)
at async ModuleJob.run (internal/modules/esm/module_job.js:165:5)
at async Loader.import (internal/modules/esm/loader.js:177:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
If I use import like what the error tip says:
import pkg from '#reduxjs/toolkit';
const { createSlice, configureStore } = pkg;
All is OK.
What I want to ask is:
It gives me a wrong example in the official website of Redux? Or Just I run the example with a wrong way?
The following is the detail information.
My Node.js version is: v14.17.3
1 Init a node project:
mkdir redux_01
cd redux_01
yarn init
yarn add #reduxjs/toolkit
2 Modify the 'package.json', add a line in it:
"type":"module"
3 Create a file 'index.js' with the "Redux Toolkit Example" code parsed from https://redux.js.org/introduction/getting-started.
import { createSlice, configureStore } from '#reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0
},
reducers: {
incremented: state => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1
},
decremented: state => {
state.value -= 1
}
}
})
export const { incremented, decremented } = counterSlice.actions
const store = configureStore({
reducer: counterSlice.reducer
})
// Can still subscribe to the store
store.subscribe(() => console.log(store.getState()))
// Still pass action objects to `dispatch`, but they're created for us
store.dispatch(incremented())
// {value: 1}
store.dispatch(incremented())
// {value: 2}
store.dispatch(decremented())
// {value: 1}
4 Now I run it like this:
node index.js
I then got that error message that I just mentioned.
The reason for the error is explained here:
https://lightrun.com/answers/reduxjs-redux-toolkit-cannot-import-redux-toolkit-from-a-nodejs-esm-module "here"
solution:
import * as toolkitRaw from '#reduxjs/toolkit';
const { createSlice,configureStore } = toolkitRaw.default ?? toolkitRaw;
or in Typescript:
import * as toolkitRaw from '#reduxjs/toolkit';

Jest - getting error when mocking FS modules and calling config module

I'm writing unit tests with Jest trying to test a module which uses FS.
The module file:
import fs from 'fs';
import logger from './logger.utils';
export const getNumberOfFiles = async (targetDir: string): Promise<number> => {
// get number of folders
logger.info(`getNumberOfFiles from ${targetDir}/${fileName}`);
const numberOfFiles = await fs.readdirSync(targetDir);
return numberOfFiles.length;
};
Test file
import fs from 'fs';
import { getNumberOfFiles } from '../../src/utils/fs.utils';
jest.mock('fs');
describe('fs.utils', () => {
describe('getNumberOfFiles', () => {
it('Should return number', async () => {
fs.readdirSync = jest.fn();
const readdirSyncMock = fs.readdirSync = jest.fn();
readdirSyncMock.mockResolvedValue([1, 2, 3]);
const result = await getNumberOfFiles('targetDir');
expect(result).toEqual(3);
expect(readdirSyncMock.mock.calls.length).toEqual(1);
});
});
});
When I run the test file, I get the following error:
Config file ..../config/runtime.json cannot be read. Error code is: undefined. Error message is: Cannot read property 'replace' of undefined
1 | const cheggLogger = require('#chegg/logger');
2 | import loggingContext from './loggingContext';
> 3 | import config from 'config';
| ^
4 | import os from 'os';
5 | import constants from '../../config/constants';
6 |
at Config.Object.<anonymous>.util.parseFile (node_modules/config/lib/config.js:789:13)
at Config.Object.<anonymous>.util.loadFileConfigs (node_modules/config/lib/config.js:666:26)
at new Config (node_modules/config/lib/config.js:116:27)
at Object.<anonymous> (node_modules/config/lib/config.js:1459:31)
at Object.<anonymous> (src/utils/logger.utils.ts:3:1)
Content of logger.utils.ts
const internalLogger = require('internalLogger');
import loggingContext from './loggingContext';
import config from 'config';
import os from 'os';
import constants from '../../config/constants';
const logger = internalLogger.createLogger({
level: config.get(constants.LOG_LEVEL)
});
export default logger;
I assume that config is using FS, and once I mock the module, it fails.
How can I resolve this? Please advise
I'm guessing the problem comes from config also using the fs api but you are now mock entire module fs which makes all methods should be mocked before using.
But I have an idea for you by using jest.doMock which you can provide a factory for each test and just mock only method we need. Here is a draft idea:
describe('fs.utils', () => {
describe('getNumberOfFiles', () => {
it('Should return number', async () => {
jest.doMock('fs', () => ({
// Keep other methods still working so `config` or others can use
// so make sure we don't break anything
...jest.requireActual('fs'),
readdirSync: jest.fn(pathUrl => {
// Mock for our test path since `config` also uses this method :(
return pathUrl === 'targetDir' ? Promise.resolve([1, 2, 3]) : jest.requireActual('fs').readdirSync(pathUrl)
})
}));
// One of the thing we should change is to switch `require` here
// to make sure the mock is happened before we actually require the code
// we can also use `import` here but requires us do a bit more thing
// so I keep thing simple by using `require`
const {getNumberOfFiles} = require('../../src/utils/fs.utils');
const result = await getNumberOfFiles('targetDir');
expect(result).toEqual(3);
// you might stop assert this as well
// expect(readdirSyncMock.mock.calls.length).toEqual(1);
});
});
});
Just also want to check, if you created a config file as described here: https://www.npmjs.com/package/config#quick-start

How to remove TypeError: "x" is not a function?

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.

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

Resources