SyntaxError: Unexpected reserved word "await" - javascript

I keep getting this error even thought I am in a asynchronous function...
import { dirname, join } from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export async function importer(client) {
const dir = join(__dirname, "../../commands/")
const commandCategories = readdirSync(dir)
for (let cat of commandCategories) {
const commandFiles = readdirSync(join(dir, cat)).filter(files => files.endsWith(".js"));
for (const file of commandFiles) {
const command = await import(join(dir, cat, file));
client.commands.set(command.default.name, command.default);
}
}
}
Is there something I am missing? I definitely need the await part in import in const command. It imports a few commands then it drops the mentioned error in title on the console output.
Thanks.

The problem isn't the importer code, it's in one of the modules you attempted to import (and import crashes on parsing it)!
It's a bug in node that such a non-helpful error is thrown when this syntax error is encountered during dynamic import.
Try logging the filenames before importing them so you can see at which file it crashes. Once you know which file failed to parse, do a static import of it for testing, so you can get a proper error that tells you which line has the issue.

Related

I am getting a required error using graphql tools

I am building a gql server application using apollo server.
When I try to load my .graphql files using import { loadFilesSync } from '#graphql-tools/load-files', this works very well, but when I load my resolver files, i get an error
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /userpath/index.js from /userpath/server-gql/noop.js not supported.
Instead change the require of index.js in /userpath/server-gql/noop.js to a dynamic import() which is available in all CommonJS modules.
at Object.newLoader [as .js] (/userpath/server-gql/node_modules/pirates/lib/index.js:141:7)
at file:///userpath/server-gql/node_modules/#graphql-tools/load-files/esm/index.js:104:33
at Array.map (<anonymous>)
at loadFilesSync (file:///userpath/server-gql/node_modules/#graphql-tools/load-files/esm/index.js:95:10)
at file:///userpath/server-gql/schema.js:20:24
at async Promise.all (index 0) {
code: 'ERR_REQUIRE_ESM'
}
I am using "type": "module" in my package.json.
Here's my code snippet for where i get the error
import path from 'path'
import { fileURLToPath } from 'url'
import { loadFilesSync } from '#graphql-tools/load-files'
import { mergeTypeDefs, mergeResolvers } from '#graphql-tools/merge'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const typesArray = loadFilesSync(path.join(__dirname, '.'), {
recursive: true,
extensions: ['graphql'],
})
const resolversArray = loadFilesSync(path.join(__dirname, './graphql/**/*.resolvers.js'), {
recursive: true,
extensions: ['js'],
})
const newResolversArray = resolversArray.slice(1)
export const typeDefs = mergeTypeDefs(typesArray)
export const resolvers = mergeResolvers(newResolversArray)
I think the error occurs in the resolvers array.
I was running into a very similar issue and found this workaround/solution worked for me: https://github.com/ardatan/graphql-tools/issues/1750#issuecomment-655828240
I had to modify that answer a bit to get it working in my codebase...below is what my own resolverFiles snippet now looks like (I'm not 100% sure what your import/naming conventions look like, or I'd try to apply this to your code snippet).
I have a mixed, nested directory schema/ that contains resolver files of the format SomethingResolvers.ts. Each of these look like the following (I'm using codegen):
import { Resolvers } from "../../generated/graphql";
export const resolvers: Resolvers = { /* resolver implementations */ };
const resolverFiles = await loadFiles(
path.join(__dirname, "**/*Resolvers.js"),
{
requireMethod: async (path) => {
const module = await import(pathToFileURL(path).toString());
return module["resolvers"];
},
recursive: true,
}
);

Why are imported modules on serverless functions undefined?

TL;DR - why do imports return undefined? Especially for native Node modules like path?
I have a very small test application, built with Vite, that has a single endpoint in the /api directory. I created this just to play around with Vite + Vercel.
I have only 2 module imports for my endpoint - path and fs-extra. Both are returning as undefined. I was getting cannot read join of undefined errors with the path module, so I wrapped everything in a try/catch just to see if the endpoint responds. It does. See my code below.
import type {VercelRequest, VercelResponse} from '#vercel/node'
import path from 'node:path' // I've also tried 'path'
import fs from 'fs-extra'
export default function handler(req: VercelRequest, res: VercelResponse) {
// Both of these log 'undefined' on my Vercel dashboard for function logs.
console.log('path module:', path)
console.log('fs module:', fs)
try {
// https://vercel.com/guides/how-can-i-use-files-in-serverless-functions
const pathFromProjectRootToFile = '/api/usersData.json'
const usersDataFilePath = path.join( // THIS IS WHERE THE ERROR HAPPENS 🙃
process.cwd(),
pathFromProjectRootToFile
)
const usersData = fs.readJSONSync(usersDataFilePath)
res.json({users: usersData})
} catch (e) {
res.json({error: errorToObject(e as Error)})
}
}
function errorToObject(err?: Error): Record<string, string> | null {
if (!err || !(err instanceof Error)) return null
const obj: Record<string, string> = {}
Object.getOwnPropertyNames(err).forEach(prop => {
const value = err[prop as keyof Error]
if (typeof value !== 'string') return
obj[prop] = value
})
return obj
}
As an aside, instead of node:path I also tried just path, but same thing - undefined. And I do have fs-extra as a dependency in my package.json.
When deploying a Vite app on Vercel and utilizing the /api directory for a back end with Serverless Functions, Node modules need to be imported via require, not import. The import syntax works for types and local modules. See this answer (and conversation) in Vercel's community discussions.
import type {VercelRequest, VercelResponse} from '#vercel/node'
import localModule from '../myLocalModule'
const path = require('path')
const fsOriginal = require('fs')
const fs = require('fs-extra')
// Rest of the file here...

Error [ERR_REQUIRE_ESM]: require() of ES Module /app/node_modules/got/dist/source/index.js from /app/commands/Image/meme.js not supported

Code:
const { EmbedBuilder } = require("discord.js");
const got = require("got");
module.exports = {
name: "meme",
description: "Shows an image of a meme!",
run: async (client, message, args) => {
got("https://www.reddit.com/r/memes/random/.json").then(response => {
const [list] = JSON.parse(response.body);
const [post] = list.data.children;
const permalink = post.data.permalink;
const memeUrl = `https://reddit.com${post.data.permalink}`;
const memeImage = post.data.url;
const memeTitle = post.data.title;
const memeUpvotes = post.data.ups;
const memeNumComments = post.data.num_comments;
const memeEmbed = new EmbedBuilder()
.setTitle(`${memeTitle}`)
.setURL(`${memeUrl}`)
.setColor("Random")
.setImage(memeImage)
.setFooter({ text: `👍 ${memeUpvotes} | 💬 ${memeNumComments}` });
message.reply({ embeds: [memeEmbed] });
});
}
};
Error:
const got = require("got");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module
/app/node_modules/got/dist/source/index.js from /app/commands/Image/meme.js not supported.
I’m not too sure what this ESM is, I’ve never dealt with it before, therefore I don’t know what to do to fix this.
Kinda think it’s got to do something with the package itself, but like I said I’m clueless as I’ve never had this error before.
got is a native ESM and no longer provides a CommonJS export.
Use ESM
To use the latest version, you'll have to convert to ESM:
you need to add "type": "module" to your package.json
replace all require()s and module.exports with import and export
Downgrade got
Another option is to downgrade got to v11.8.3 as it's pretty stable:
You can run npm i got#11.8.3 in your console.

fs.readFile() or fs.readFileSync() not a function exception but why?

I am using the fs module with the following import code
import fs = require('fs')
The code runs until encountering this exception at the second line of the TypeScript codes below
const filePath = 'data/soylent-uist2010/userSegments.json'
const seg = fs.readFileSync(filePath, {
encoding: 'utf8',
})
However, if I supply the path argument of readFileSync as a raw string (as below), it works as normal (value is assigned).
const seg = fs.readFileSync('data/soylent-uist2010/userSegments.json', {
encoding: 'utf8',
})
The error stack trace is as below,
Viewer.tsx:155 Uncaught (in promise) TypeError: fs.readFileSync is not a function
at Viewer.<anonymous> (Viewer.tsx:155)
at step (io.ts:106)
at Object.next (io.ts:106)
at io.ts:106
at new Promise (<anonymous>)
at __awaiter (io.ts:106)
at Viewer._this.loadFiles (Viewer.tsx:135)
at Viewer.<anonymous> (Viewer.tsx:98)
at step (io.ts:106)
at Object.next (io.ts:106)
A longer code snippet is as below. I suspect if the async keyword (in the class method) would require an await keyword before fs.readFile()
loadFiles = async () => {
this.setState({ pages: [] });
const {
pageNumbersToLoad,
pathInfo: { pdfDir, pdfRootDir }
} = this.props;
const fullDirPath = path.join(pdfRootDir, pdfDir);
const pdfPath = path.join(fullDirPath, pdfDir + ".pdf");
**const seg = fs.readFile(...);**
Because fs does not have a default export you need to import like so:
import * as fs from 'fs'
You are mixing javascript standards.
If you choose to use the older javascript ES5 standard, then your code should like like this:
var fs = require('fs');
However, if you're going to use the newer ES6 (and beyond) standard, you would use the import statement like so:
import fs from 'fs';
You seem to be combining the two, hence your error.
NOTE: Because fs has a default export that exports the fs module, you don't need the import * as syntax. See this post for a more detailed explanation.

Module Import error - cannot find module

I was trying to import the module dynamically in ES6 on Meteor application. But getting an error cannot find module. The same import works when I'm using the static import statement.
Please have a look at the below code -
const JOBS = ['update-report-cron'];
const jobs = {
start() {
JOBS.forEach((job) => {
console.log(`job ${job} has been started`);
let fileName = './' + job + '.js';
console.log(require(fileName));
})
}
};
module.exports = {jobs};
ERROR - Cannot find module './update-report-cron.js'
Try
export default const jobs = {
// your code
}
When you import, use
import { jobs } from './update-report-cron.js'
Ru's answer is not correct, not sure how it's your answer.
Try
export default const jobs = {
// your code
}
When you import, use
import jobs from './update-report-cron.js'

Categories

Resources