Config param are undefined in error handler - javascript

I have a config file that just sets the process.env data to params.
It works fine and I can use it correctly everywhere but on my unexpected exceptions handler I can't use it... all the params from the config file are undefined.
my config file:
module.exports = {
env: process.env.NODE_ENV,
};
here is my uncaught exception catcher:
process.on('uncaughtException', (error) => {
errorManagement.handler.handleError(error);
if (!errorManagement.handler.isTrustedError(error)) process.exit(1);
});
and here is error handler, env is undefined, everywhere else env is defined
const {
env,
} = require('../../config');
const logger = require('../../libraries/logger');
const mailer = require('../../libraries/mailer');
function ErrorHandler() {
this.handleError = async (err) => {
console.log(env);
};
}
module.exports.handler = new ErrorHandler();
tree of my project folder:
EDIT:
I found the problem but I'm still not sure why it happened...
in my config.js file I did:
const errorManager = require('./components/errorManagement');
[
'DB_USER',
].forEach((name) => {
if (typeof process.env[name] === 'undefined') {
throw new errorManager.AppError('Environment var missing', 500, `Environment variable ${name} is missing`, true);
}
});
when I deleted the error manager and used express Error everything worked as expected

Related

mocking fs module causes Fs.statSync is not a function error

node version: 14.20.0
jest version: 28.1.1
ts-jest version: 28.0.5
I have following function which is to be tested
uploadFile.ts
import * as fs from 'fs';
export async function uploadFile(containerName, customerId, fileName, filePath, logCtx){
fs.stat(filePath, (err, stats) => {
if (err) {
logger.error({err, ...logCtx}, `File doesn't exist. File path: ${filePath}`);
} else {
logger.info(logCtx, `File size: ${stats.size}`);
if(stats.size < 1){
logger.error({err, ...logCtx}, `Byte size is ${stats.size} - File is empty. File path: ${filePath}`);
throw new Error("File is empty.")
}
}
});
// do some other things
}
The uploadFile function uses fs module and I decided to mock it since we don't need to do anything with files for testing
uploadFile.test.js
// mock fs package
const fs = { stat: jest.fn(), createReadStream: jest.fn() };
jest.mock("fs", () => {
return fs;
});
it("should call fs.stat once", async () => {
// Arrange
const { uploadFile } = require("../../../lib/global/uploadFile");
const containerName = "qz";
const customerId = "w3";
const fileName = "none.pdf";
const filePath = "src/services/none.pdf";
const logCtx = {};
// Act
await uploadFile(containerName, customerId, fileName, filePath, logCtx);
// Assert
expect(fs.stat).toBeCalledWith(filePath, expect.any(Function));
expect(fs.stat).toBeCalledTimes(1);
});
when running the above test file, test case fails and shows the following error
● should call fs.stat once
require-at: stat 'C:\guardian group\c360-accounts' failed: Fs.statSync is not a function
at makeIt (node_modules/require-at/require-at.js:19:15)
at requireAt (node_modules/require-at/require-at.js:35:10)
at Object.<anonymous> (node_modules/mongoose/node_modules/mongodb/node_modules/optional-require/src/index.ts:318:64)
at Object.<anonymous> (node_modules/mongoose/node_modules/mongodb/node_modules/optional-require/index.js:8:13)
I have changed the mock of "fs" to the following hopeing it would resolve the error, and it is showing a different error instead.
const fs = { stat: jest.fn(), createReadStream: jest.fn(), statSync: jest.fn() };
The error
● should call fs.stat once
require-at: not a directory: 'C:\guardian group\c360-accounts'
at makeIt (node_modules/require-at/require-at.js:23:28)
at makeIt (node_modules/require-at/require-at.js:24:16)
at requireAt (node_modules/require-at/require-at.js:35:10)
at Object.<anonymous> (node_modules/mongoose/node_modules/mongodb/node_modules/optional-require/src/index.ts:318:64)
at Object.<anonymous> (node_modules/mongoose/node_modules/mongodb/node_modules/optional-require/index.js:8:13)
What's happening here, am I missing something?
Thanks in advance

Clarifai api referenceerror : process is not defined

I get such an error on npm start on clarifai api
[1]: https://i.stack.imgur.com/pHRNz.png
Open bootstrap:27:
// Execute the module function
try {
var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: __webpack_require__ };
__webpack_require__.i.forEach(function(handler) { handler(execOptions); });
module = execOptions.module;
execOptions.factory.call(module.exports, module, module.exports, execOptions.require);
} catch(e) {
module.error = e;
throw e;
}
// Flag the module as loaded
module.loaded = true;
// Return the exports of the module
return module.exports;
}
and my App.js details;
const app = new Clarifai.App({
apiKey: '****',
})
///
onButtonSubmit = () => {
console.log('click')
app.models
.predict(
'45fb9a671625463fa646c3523a3087d5',
'https://samples.clarifai.com/metro-north.jpg'
)
.then(
function (response) {
console.log(response)
},
function (err) {
//
}
)
}
I am getting this error before render in console.log. what would be the reason?
Happy coding day! :)
As stated in the documentation you need to use Broserify. You are missing NodeJS globals. Please let us know if this does not work for you as this library is unfortunately not under active maintenance currently.

Discordjs v12 | cannot find module ../undefined/help.js

My bot has a command located in /commands/developer/reload.js and it's purpose is to unload a command then load it again. But when trying to find the commands folder it throws an error saying Cannot find module '../undefined/help.js' but the path is ../misc/help.js
Code:
const fs = require('fs');
module.exports = {
name: 'reload',
description: 'Reloads a command',
args: true,
usage: '<command_name>',
cooldown: 1,
aliases: ['rl', 'restart'],
execute(message, args) {
const commandName = args[0].toLowerCase();
const command = message.client.commands.get(commandName) || message.client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if(!command) {
return message.channel.send(`There is no command called '${commandName}'`);
}
// commandFolders returns undefined
const commandFolders = fs.readdirSync('./commands');
// Also returns undefined
const folderName = commandFolders.find(folder => {
fs.readdirSync(`./commands/${folder}`).includes(`${command.name}.js`);
})
// Command errors out here
delete require.cache[require.resolve(`../${folderName}/${command.name}.js`)];
// This part never runs.
try {
const newCommand = require(`../${folderName}/${command.name}.js`);
message.client.commands.set(newCommand.name, newCommand);
message.channel.send(`Command '${newCommand.name}' was reload successfully`)
} catch (err) {
console.error(err);
message.channel.send(`There was an error while reloading a Command.`)
}
}
}
The reason why you are getting the folder as undefined is because you are not returning the folder you are trying to find in the folderName function. It is trying to find a folder with the command and even if it does, you are not doing anything with it, you are not returning it or logging it into the console. So you just have to return it, the folderName function might look something like this:
const folderName = commandFolders.find(folder => fs.readdirSync(`commands/${folder}`).includes(`${command.name}.js`)) // If you want a one-liner
// Or
const folderName = commandFolders.find(folder => {
return fs.readdirSync(`commands/${folder}`).includes(`${command.name}.js`)
})
If the error persists, the error is most likely there because the path is not correct. So in that case, please provide the folder structure of your bot

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received an instance of Object

I am using the source code from a security rules tutorial to attempt to do integration testing with Jest for my Javascript async function async_create_post, used for my firebase HTTP function create_post The files involved has a directory structure of the following:
Testing file: root/tests/handlers/posts.test.js
File to be tested: root/functions/handlers/posts.js
Helper code from the tutorial: root/tests/rules/helpers.js
And here is the source code that is involved:
posts.test.js
const { setup, teardown} = require("../rules/helpers");
const {
async_get_all_undeleted_posts,
async_get_post,
async_delete_post,
async_create_post
} = require("../../functions/handlers/posts");
describe("Post Creation", () => {
afterEach(async () => {
await teardown();
});
test("should create a post", async () => {
const db = await setup();
const malloryUID = "non-existent uid";
const firstPost = {
body: "First post from Mallory",
author_id: malloryUID,
images: ["url1", "url2"]
}
const before_post_snapshot = await db.collection("posts").get();
expect(before_post_snapshot.docs.length).toBe(0);
await async_create_post(firstPost); //fails at this point, expected to create a new post, but instead threw an error
const after_post_snapshot = await db.collection("posts").get();
expect(after_post_snapshot.docs.length).toBe(1);
});
});
posts.js
const {admin, db } = require('../util/admin');
//admin.initializeApp(config); //my credentials
//const db = admin.firestore();
const { uuid } = require("uuidv4");
const {
success_response,
error_response
} = require("../util/validators");
exports.async_create_post = async (data, context) => {
try {
const images = [];
data.images.forEach((url) => {
images.push({
uid: uuid(),
url: url
});
})
const postRecord = {
body: data.body,
images: images,
last_updated: admin.firestore.FieldValue.serverTimestamp(),
like_count: 0,
comment_count: 0,
deleted: false,
author_id: data.author_id
};
const generatedToken = uuid();
await db
.collection("posts")
.doc(generatedToken)
.set(postRecord);
// return success_response();
return success_response(generatedToken);
} catch (error) {
console.log("Error in creation of post", error);
return error_response(error);
}
}
When I run the test in Webstorm IDE, with 1 terminal running Firebase emulators:start , I get the following error message.
console.log
Error in creation of post TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received an instance of Object
at validateString (internal/validators.js:120:11)
at Object.basename (path.js:1156:5)
at GrpcClient.loadProto (/Users/isaac/Desktop/project/functions/node_modules/google-gax/src/grpc.ts:166:23)
at new FirestoreClient (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/v1/firestore_client.js:118:38)
at ClientPool.clientFactory (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/index.js:330:26)
at ClientPool.acquire (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/pool.js:87:35)
at ClientPool.run (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/pool.js:164:29)
at Firestore.request (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/index.js:961:33)
at WriteBatch.commit_ (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/write-batch.js:485:48)
at exports.async_create_post (/Users/isaac/Desktop/project/functions/handlers/posts.js:36:5) {
code: 'ERR_INVALID_ARG_TYPE'
}
at exports.async_create_post (/Users/isaac/Desktop/project/functions/handlers/posts.js:44:13)
Error: expect(received).toBe(expected) // Object.is equality
Expected: 1
Received: 0
<Click to see difference>
at Object.<anonymous> (/Users/isaac/Desktop/project/tests/handlers/posts.test.js:59:45)
Error in creation of post comes from the console.log("Error in creation of post", error); in posts.js, so the error is shown in the title of this post.
I want to know why calling the async_create_post from posts.test.js will cause this error and does not populate my database with an additional record as expected behaviour. Do inform me if more information is required to solve the problem.
Here are some code snippets that may give more context.
helpers.js [Copied from the repository]
const firebase = require("#firebase/testing");
const fs = require("fs");
module.exports.setup = async (auth, data) => {
const projectId = `rules-spec-${Date.now()}`;
const app = firebase.initializeTestApp({
projectId,
auth
});
const db = app.firestore();
// Apply the test rules so we can write documents
await firebase.loadFirestoreRules({
projectId,
rules: fs.readFileSync("firestore-test.rules", "utf8")
});
// write mock documents if any
if (data) {
for (const key in data) {
const ref = db.doc(key); // This means the key should point directly to a document
await ref.set(data[key]);
}
}
// Apply the actual rules for the project
await firebase.loadFirestoreRules({
projectId,
rules: fs.readFileSync("firestore.rules", "utf8")
});
return db;
// return firebase;
};
module.exports.teardown = async () => {
// Delete all apps currently running in the firebase simulated environment
Promise.all(firebase.apps().map(app => app.delete()));
};
// Add extensions onto the expect method
expect.extend({
async toAllow(testPromise) {
let pass = false;
try {
await firebase.assertSucceeds(testPromise);
pass = true;
} catch (error) {
// log error to see which rules caused the test to fail
console.log(error);
}
return {
pass,
message: () =>
"Expected Firebase operation to be allowed, but it was denied"
};
}
});
expect.extend({
async toDeny(testPromise) {
let pass = false;
try {
await firebase.assertFails(testPromise);
pass = true;
} catch (error) {
// log error to see which rules caused the test to fail
console.log(error);
}
return {
pass,
message: () =>
"Expected Firebase operation to be denied, but it was allowed"
};
}
});
index.js
const functions = require('firebase-functions');
const {
async_get_all_undeleted_posts,
async_get_post,
async_delete_post,
async_create_post
} = require('./handlers/posts');
exports.create_post = functions.https.onCall(async_create_post);
The error message means that a method of the path module (like path.join) expects one of its arguments to be a string but got something else.
I found the offending line by binary search commenting the program until the error was gone.
Maybe one of your modules uses path and you supply the wrong arguments.

Why is process.env undefined in module?

I'm beginner with nodejs and I want environment variables shared through modules. I read those variables with dotenv package. But in next required module process.env is undefined.
app.js
console.log(require('dotenv').config())
console.log(process.env.NODE_ENV);
require('./task')
task.js
console.log(process.env);
console.log(process.env.NODE_ENV);
.env
NODE_ENV=development
PORT=8080
console log
{ parsed: { NODE_ENV: 'development', PORT: '8080' } }
development
undefined
E:\msf\nodejs_prj\compositor\task.js:2
console.log(process.env.NODE_ENV);
^
TypeError: Cannot read property 'NODE_ENV' of undefined
at Object.<anonymous> ...
I created new clean project with provided code and it works also for me. That means it's related to something else. This node.js is weard about errors.
This is my whole code from task.js
const fs = require('fs')
const path = require('path')
const decompress = require('decompress')
const dir = './upload'
console.log(process, process.env)
function process() {
console.log('cron - process data');
fs.readdir(dir, (err, files) => {
if (err) return
files.forEach(file => {
if (path.extname(file) != '.zip') return
let target = path.join(dir, path.basename(file).replace(path.extname(file), ''))
unlinkDirSync(target)
decompress(path.join(dir, file), target).then(files => {
console.log(files);
console.log('done!');
//todo process unzipped files
//todo delete unzipped directory and zip file
})
})
})
}
function unlinkDirSync(dir_path) {
if (fs.existsSync(dir_path)) {
fs.readdirSync(dir_path).forEach(function (entry) {
var entry_path = path.join(dir_path, entry);
if (fs.lstatSync(entry_path).isDirectory()) {
unlinkDirSync(entry_path);
} else {
fs.unlinkSync(entry_path);
}
});
fs.rmdirSync(dir_path);
}
}
if (process.env === undefined || process.env.NODE_ENV === undefined || process.env.NODE_ENV === 'production') {
console.log('starting on production')
setInterval(process, 1000 * 60)
} else {
console.log('starting on development')
setTimeout(process, 1000)
}
If I comment out the rest after console.log it works.
I'm idiot. I named function process, which is the name of system variable :D
Sorry for bothering you guys, thanks for help.
Add require('dotenv').config() in global. Also make sure .env file is in root directory of the project. I have created a sample on github https://github.com/GMaker01/basic-dotenv-example
For reference, you can look into the dotenv documentation

Categories

Resources