TypeError: feature is not a function in discord.js using WOK tutorials - discord.js

Coding DJS bot using the WOK YT tutorials as a base.
Refactored all my code and made a load-features file to load many of my commands into index.js automatically.
Here is the code for that file:
const path = require("path");
const fs = require("fs");
module.exports = (client) => {
const readFeatures = (dir) => {
const files = fs.readdirSync(path.join(__dirname, dir));
for (const file of files) {
const stat = fs.lstatSync(path.join(__dirname, dir, file));
if (stat.isDirectory()) {
readFeatures(path.join(dir, file));
} else if (file !== "load-features.js") {
const feature = require(path.join(__dirname, dir, file));
console.log(`Enabling feature "${file}"`);
feature(client);
}
}
};
readFeatures(".");
};
The error says TypeError: feature is not a function when calling feature(client). It was working fine yesterday but suddenly decided not to work.
If you need more examples of the code itself, here is a link to the tutorial repository, where this file is identical to mine and how it is connected to index.js: https://github.com/AlexzanderFlores/Worn-Off-Keys-Discord-Js/tree/master/43-Refactoring
Please advise.

Related

Loading contents of files into a NextJs app at runtime as env vars

I'm trying to load the contents of files in a specific folder as env vars accessible at process.env.SomethingHere at runtime not build time as those files don't exist at build time yet (if process.env is the right place to load those secrets, more about that in the end). I managed to write the code to read the files and create a key-value object/dictionary from them, but not sure where is the best spot in the app lifecycle to add this so it's available for both server-side middleware and client-side frontend
function readFiles(dir) {
var vars = {};
if(!fs.existsSync(dir))
{
console.log("failed to load files in directory: " + dir);
return vars;
}
// read directory
let fileNames = fs.readdirSync(dir);
if (!fileNames) {
console.log("failed to load files in directory: " + dir);
return vars;
}
fileNames.forEach((filename, index) => {
// get current file name
const name = path.parse(filename).name;
// get current file path
const filepath = path.resolve(dir, filename);
// get information about the file
let stat = fs.statSync(filepath);
if (!stat) {
console.log("failed to load file stats: " + name);
return;
}
// check if the current path is a file or a folder
const isFile = stat.isFile();
// exclude folders
if (isFile) {
let data = fs.readFileSync(filepath);
if (!data) {
console.log("failed to load file: " + name);
return;
}
let content = data.toString('utf8', 0, data.length);
// callback, do something with the file
vars[name] = content;
}
});
return vars;
}
Some background:
I'm using Azure keyvault for storing secrets and have a Kubernetes cluster with a frontend and a backend pod.
In the backend pod I was able to mount the secrets using CSI driver fetch the values at app startup and load that into the python os.environ. I'm trying to achieve the same for the frontend pod, the mounting is successful, but I haven't been able to place my code in the right spot to load the secrets into process.env if this is even the right place to add them.
ChatGPT solved the issue eventually, here is the answer:
In a Next.js application, the server-side entry point is the server.js file located in the root directory of the project. By default, this file exports the createServer function, which is used to create the Express server that handles server-side rendering of the application.
You can add your code to load the environment variables in this file by importing the readFiles function and using the Object.assign() method to merge the key-value object with the existing process.env object, like this:
env.js
function readFiles(dir) {
// existing code here
}
module.exports = readFiles;
server.js in the root directory of the project
const readFiles = require('./env');
const dir = './dir_name'
const envVars = readFiles(dir);
Object.assign(process.env, envVars);
const dev = process.env.NODE_ENV !== 'production'
const hostname = 'localhost'
const port = 3000
const {createServer} = require('next');
const app = next({ dev, hostname, port })
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer(handle).listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://${hostname}:${port}`)
});
});

Serve static javascript file from nextjs api

I need a route in website build with nextjs that sends javascript that can be used on different website to do some things.
I created new file in pages/api, let's call it sendTest.ts so it's location is pages/api/sendTest.ts. In the same folder I crated test.ts file that I want to send from sendTest.ts.
sendTest.ts
import type { NextApiRequest, NextApiResponse } from 'next'
import fs from 'fs';
import path from 'path'
const filePath = path.join(__dirname, 'test.js');
const file = fs.readFileSync(filePath);
export default function handler(
req: NextApiRequest,
res: NextApiResponse
) {
res.setHeader('Content-Type', 'text/javascript');
res.status(200).send(file)
}
test.ts
console.log('hello');
After build nextjs serves that file at website.com/api/sendTest but after bundling it ends up as
"use strict";
(() => {
var exports = {};
exports.id = 318;
exports.ids = [318];
exports.modules = {
/***/ 211:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
console.log("hello there");
/***/ })
};
;
// load runtime
var __webpack_require__ = require("../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = (__webpack_exec__(211));
module.exports = __webpack_exports__;
})();
which when used in different page as
<script src="website.com/api/sendTest"></script>
results in error
Uncaught ReferenceError: require is not defined
at sendTest:22:27
at sendTest:28:3
My question is how can I force nextjs to skip loading webpack into that file and just allow typescript to change content into javascript and serve file as is? Or is there better way to do what I want, which is sending javascript from specified nextjs route?
Got it.
I changed
const filePath = path.join(__dirname, 'test.js');
to
const filePath = path.resolve('.', 'script/test.js');
and put my script file into folder called script (name doesn't matter) in the main directory

Error creating StandardAppVersion: googleapi: Error 404: App does not exist

Hi i am trying to create a simple node app on google app standard app engine using this terraform code. This code used to work before but today i was trying to restart the whole project and re-deploy everything again and i see that i am getting an error.
compute_engine.tf
resource "google_app_engine_standard_app_version" "nodetest" {
version_id = "v1"
service = "mainApp"
runtime = "nodejs10"
instance_class = "B1"
basic_scaling {
max_instances = 1
}
entrypoint {
shell = "node test.js"
}
deployment {
files {
name = google_storage_bucket_object.object.name
source_url = "https://storage.googleapis.com/${google_storage_bucket.bucket.name}/${google_storage_bucket_object.object.name}"
}
}
delete_service_on_destroy = true
depends_on = [
google_project_service.appengine_api
]
}
resource "google_storage_bucket" "bucket" {
project = var.project_id
name = var.bucket_name
location = var.region
}
resource "google_storage_bucket_object" "object" {
name = "test.js"
bucket = google_storage_bucket.bucket.name
source = "test.js"
}
My test.js is located in the same directory as where tf is located.
test.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
I see that the files have already been deployed correctly
And the error i am getting
I tried changing the url from
"https://storage.googleapis.com/${google_storage_bucket.bucket.name}/${google_storage_bucket_object.object.name}"
To
"https://storage.cloud.com/${google_storage_bucket.bucket.name}/${google_storage_bucket_object.object.name}"
Try changing the shell = "node test.js" to shell = "node ./test.js"
Also i did take a look at GitHub Issue 4974 but is doesnt solve my problem. I did notice that when i try to terraform apply the error pretty much pop up quite fast so it seem that is stuck on a very first validation error.
Does the user that runs compute_engine.tf has "appengine.applications.create" and deploy permissions?
Also check if you set project and region in your google provider.

Failed to regiester service worker error in Next.js file

I'm using workbox-webpack-plugin to generate a service worker for me and I'm using copy-webpack-plugin move generated service worker files to the same directory as main.js. My next js config file goes like this:-
module.exports = {
webpack: (config, {isServer, buildId, dev, ...rest}) => {
if (dev) {
const devSwSrc = join(__dirname, "register-sw.js");
config.plugins.push(new CopyWebpackPlugin([devSwSrc]));
config.plugins.push(new GenerateSW({ ...defaultGenerateOpts }));
// Register SW
const originalEntry = config.entry;
config.entry = async () => {
const entries = await originalEntry();
const swCompiledPath = join(__dirname, 'register-sw-compiled.js');
if (entries['main.js'] && !entries['main.js'].includes(swCompiledPath)) {
let content = await readFile(require.resolve('./register-sw.js'), 'utf8');
await writeFile(swCompiledPath, content, 'utf8');
entries['main.js'].unshift(swCompiledPath);
}
return entries;
};
}
I'm trying to copying my service worker to the same dir as main.js which is chunk/static so that when it's fetched it should not return any error. But instead, I'm getting this error.
TypeError: Failed to register a ServiceWorker for scope ('[http://localhost:3000/](http://localhost:3000/)') with the script ('[http://localhost:3000/service-worker.js](http://localhost:3000/service-worker.js)'): A bad HTTP response code (404) was received when fetching the script.
I know this error is because it's not getting served from the same dir as main.js and I need to make some changes in copy-webpack-plugin in order to achieve that. Also I'm trying to avoid custom server.js file to server routes like /service-worker
Any help would be really appreciated. Thanks in advance

How to compile Elm with React in Browserify

I want to start using Elm in a React project, but they are not using Webpack, they are using Browserify with Gulp instead. How can I get Elm to be compiled with Browserify?
In the end, the best way around it I found was to compile the Elm code first, and only then compile the JS. This means that, unlike when using elm-webpack-loader where you can require the .elm files directly form JS, I have to require the compiled elm code.
Here is a Gulp task to compile all Main.elm files in a directory or any of its subdirectories into a single .js file. You can then require the modules with
import { Widget1, Widget2 } from "../compilation-folder/myapp.js"
Here is the task:
const path = require("path");
// const execSync = require("child_process").execSync;
const shell = require("gulp-shell");
const glob = require("glob");
// Compiles all Main.elm files in a specified src folder and its subfolders
// into the output file specified
module.exports = (src, dest, outname) => {
const output = path.join(dest, `${outname}`);
return done => {
glob(src + "/**/Main.elm", {}, (err, filesArray) => {
const files = filesArray.join(" ");
shell.task(`elm-make --yes ${files} --output=${output}`)(done)
})
}
};
You can use it like this:
const buildElm = require("./fileWithCodeAbove.js")
gulp.task("build-elm", buildElm("./elm-directory", "./build-directory", "myapp.js");

Resources