require() function with an object param? - javascript

I'm looking at a require() function that looks like this and I have no clue what it does. It seems like it gets an array of files and builds a string of some try-catch blocks with interpolated module names, but I'm a bit hazy on the specifics.
require('./modules/**/index.js', {mode: (base, files) => {
return files.map(module => {
return `
try {
require('${module}');
} catch (e) {
debug.error('Failed to ${module}', e.stack);
}
`;
}).join(' ');
}});
I looked for params in the Node documentation (https://nodejs.org/api/modules.html#modules_require_id) and couldn't find anything. Anyone have any ideas?

It's not a regular require.
It's a require-globify package. It allows globbing expressions to require. mode key of second parameter defines how to handle the calls.

Related

How can I use an IIFE script in a Deno program?

We have a library of JS that currently must target ES3 because a production product uses a tool with an older JS engine, and this is non-negotiable. But I need to be able to use this library in Deno, and I can't convert it to ES modules. The library is currently using function-closure modules, ala Crockford, where every source is a single constructor function like this:
function ModuleName() {
"use strict";
...
}
and then the module is consumed with let mod=new ModuleName();.
Is there any way I can use these in deno? I don't care how, exactly -- I can load the script and eval it if necessary, but it would be nice to just use some form of import.
I've tried loading the script file and using eval and using Function, in various forms, and about every variation of import documented. I've scoured the Deno docs and tried every search I can think of. All to no avail.
Any suggestions would be appreciated.
The key was to wrap the source file with Function(return (+ ... +);)() to get a reference to the module constructor function, which can then be constructed. I'm open to better ideas, but this works for my case.
function createModule(pthORurl, ...args) {
try {
let mod = Function("return ("+Deno.readTextFileSync(pthORurl)+");")();
if(typeof(mod)!=="function") { throw Error("Loaded module is type '"+typeof(mod)+"' not type 'function'"); }
mod = new mod(...args);
if(typeof(mod)!=="object") { throw Error("Loaded module is type '"+typeof(mod)+"' not type 'object'"); }
return mod;
}
catch(err) { err.message += " (loading "+pthORurl+")"; throw err; }
}

is there a way to overwrite catch function in js

here is the code
function xyz() {
try {
var a = someexecutions();
handlesuccess(a)
} catch (err) {
handleerror(err)
}
}
this kind of function written any many times in my codebase I want
function xyz() {
try {
var a = someexecutions();
handlesuccess(a)
} catch (err) {
console.log(`function xyz throw ${err} from file ${__fileName}`)
handleerror(err)
}
}
but writing this anywhere is very huge work since there are more than 100 functions so I think if I am able to overwrite the catch function then it will work for me somehow. So is there any way for doing this
No, there isn't. It's part of the language. What you can do:
Use your IDE to search & replace
Put your code inside handleerror function
Hundred instances are not that much, you can do it :)
This is not possible. If handleerror is a globally shared function you may be able to extract the error's context function name through the non-standard stack error property or arguments.callee.
Otherwise you could possibly use a regex-based find and replace or a parser to rewrite the code programmatically.

TypeError [EMOJI_TYPE]: Emoji must be a string or GuildEmoji/ReactionEmoji

so in my module.js, I put
function emoji(e) {
return client.emojis.cache.find(emoji => emoji.name === e)
}
module.exports = {
emoji
}
and in index,js, I put
const module = require("./module.js")
msg.react(module.emoji('check'))
So what I'm making is that I want the bot to react with a custom emoji I uploaded named 'check'. In case I could use this in the future, I decided to make a function so that the bot(client) can find emoji easily without me copy/pasting "client.emojis.find(emoji => emoji.name === blabla)" everytime when needed.
But when I run it, the console says
TypeError [EMOJI_TYPE]: Emoji must be a string or GuildEmoji/ReactionEmoji
The reason why I'm posting this is because when I put that function block into index.js, it works perfectly. But when I put it into module.js and use it by module exporting, the error occurs as I mentioned.
Can anyone tell me what I missed?
I havent tested this, but i have a few things I think you should try:
What Elitezen suggested, which is specifically requiring the emoji function from the module:
const { emoji } = require("./module")
what would also probably work is just to do
module.exports = emoji //instead of module.exports = { emoji }
^^ this means it only exports the emoji function, instead of exporting a dictionary containing the function.
After my edits, your full code would look like this:
function emoji(e, client) {
return client.emojis.cache.find(emoji => emoji.name === e)
}
module.exports = emoji
const module = require("./module.js")
msg.react(module('check', client))

Best way to create something like lodash get in typescript?

I am trying to find the best way to create a type-safe version of lodash get() function.
I did my research and I have come up with a get function that works something like this (The actual types are a bit more complicated):
export function get<Target>(getter: () => Target, defaultValue: Target): Target {
try {
return getter();
} catch (e) {
return defaultValue;
}
}
This works nice, and it allows me to do something like this:
get(() => a!.b!.c!.d, 'someDefaultValue');
but I really don't like the "!" syntax. It feels unneeded.
I have found some alternative solutions for this, that try to convert the given object into an "all optional" type (Partial), but things get nasty when trying to convert it back to the real object and I don't like it.
Is there a way to get rid of the "!" syntax?
I even thought of maybe writing a custom rule for typescript that will swallow the "Object is possibly 'undefined'.ts(2532)" error if we are inside the context of my get function, but I don't know if typescript allows this kind of stuff.
Any suggestions?
Edit: for the ones who are interested in the full declaration of the function, I used function overloading to cover all the cases so it looks like this:
export function get<Target>(getter: () => Target): Target | undefined;
export function get<Target>(getter: () => Target, defaultValue: Target): Target;
export function get(getter: () => any, defaultValue?: any): any {
try {
return getter();
} catch (e) {
return defaultValue;
}
}

NodeJS Group Functions Under A Sub-Class

perhaps I have not worded the title correctly. Below is the explanation of what I'm trying to do.
I'm creating a helper.js file for my project. Inside it contains many functions, one I've pasted below. I export this function using module.exports.
function generateInternalError(message, stack_trace) {
if (process.env.NODE_ENV == 'dev') {
console.log({ message: message, stack_trace: stack_trace });
} else {
console.log({message: message});
}
}
module.exports = {
generateInternalError: generateInternalError
};
Where I want to utilize this function I would call:
helper.generateInternalError('Not Found',new Error().stack);
And it works as expected.
But, what I have been tasked with, is creating categories of functions. Essentially I need the following:
helper.errors.generateInternalError('Not Found',new Error().stack);
I can not seem to figure out the right way to export a class of functions or an object of functions in NodeJS such that I don't get an error like:
TypeError: helper.errors.generateClientError is not a function
Any assistance is appreciated.
Thank you
The module.exports property of a file is simply an object that maps names to functions. You can define it arbitrarily, for example:
module.exports = {
errors: {
generateInternalError,
...
},
...
};
Then, require('./helper').errors.generateInternalError will be defined.
helpers is just noise if everything is a helper, so drop that. Just use regular modules and unless you are sure you only have one function in that category export multiple functions. If you only export one function with module.exports then you don't need to do that as a property of an object which also means you can just say const genError=require('./errors')
Don't make something like helpers.errors.someErrorFunc because helpers is noise and you make categories with just separate module files. Don't try to make Node.js look like Java or something equally horrible.
It might be better to structure your helper sub classes in separate files.
Example
src/helpers.js
src/helpers/
src/helpers/errors.js
File helpers.js
module.exports = {
errors: require('./helpers/errors')
}
File helpers/errors.js
module.exports = {
generateInternalError: function(){
//write some internal error code here
}
};
Structuring your code like this will keep your root helpers file very organized and create a pattern that is easy to replicate for new subclasses.
If you prefer a less modular approach you could simply just return one big JSON object as other's have demonstrated...
module.exports = {
errors: {
generateInternalError: function(){
//internal error code
},
generateDatabaseError: function(){
//db error code
}
}
}

Categories

Resources