When trying to access a specific key in a JavaScript object, it may

I am currently working on optimizing the performance of my express application for production. I came across a helpful video tutorial at https://www.youtube.com/watch?v=WiZ2Py97rio, where the presenter explains a config object with keys for 'development', 'production' & 'test'.

Following the example in the video, I created a similar configuration:

import bunyan from "bunyan";

const loggers = {
    development: () => bunyan.createLogger({name: "development", level: "debug"}),
    production: () => bunyan.createLogger({name: "production", level: "info"}),
    test: () => bunyan.createLogger({name: "test", level: "fatal"}),
}

const config = {
    development: {
        log: loggers.development
    },
    production: {
        log: loggers.production
    },
    test: {
        log: loggers.test
    }
};

export default config;

However, when attempting to implement this configuration, it seems to only work in development mode:

import configObject from "./config.js";
const config = configObject[process.env.NODE_ENV || "development"];
const log = config.log();

In production, running the following code yields unexpected results:

console.log(process.env.NODE_ENV || "development");
console.log(configObject);
console.log(configObject[process.env.NODE_ENV || "development"]);

The output is as follows:

production 

{
  development: { log: [Function: development] },
  production: { log: [Function: production] },
  test: { log: [Function: test] }
}

undefined

Although it correctly identifies the environment as production and has the 'production' key in the config object, it fails to evaluate properly. Any insights on why this might be happening would be greatly appreciated.

Thank you in advance!

Answer №1

After investigating, I discovered that the root of the problem lay in my production script. The line causing issues was

"win-production": "SET NODE_ENV=production && node ./src/server.js | bunyan -o short",
. It turns out that a space after the word 'production' was causing disruptions.

This issue was resolved with the help of this resource: Compare proccess.env.NODE_ENV with String

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message: Unable to access the state property of an undefined object

I've been attempting to integrate a react sticky header into my stepper component. However, I've encountered an issue where it doesn't render when added inside my App.js file. As a result, I've started debugging the code within App.js ...

Send both the file and data in a single request to the node server

I've created an HTML form with two inputs - one for text and one for files. <form method="post" action="http://localhost:3000/users"> <input type="text" name="username" /> <input type="file" name="file" /> ...

Is there a way to extract a particular value from a JSON URL and transfer it to a JavaScript variable?

I am looking to extract current exchange rates from a JSON URL for implementation in a webpage. Specifically, I want to retrieve a particular exchange rate (such as the US Dollar) and store it in a variable for use within a JavaScript function. Below is a ...

Obtain the result of the Mongoose find operation

Greetings, I am facing a challenge with accessing elements returned from a find operation in Mongoose due to the asynchronous nature and callback functions. Below is the code for reference: function retrieveBudgets(email, callback) { models.User.f ...

What are the best practices for maintaining consistency with session variables between Express and Socket.io in a single-page application?

I am currently dealing with an issue in my single page app where the middleware is attaching my express session to my socket before a user is logged in. Refreshing the site after logging in works, but I need a more efficient solution. Is there a way to con ...

Attempting to execute a code snippet using Express framework on the local server at port 3000

Having some trouble with my initial attempt at a basic application. The Scraper.js file successfully scrapes a URL and outputs the array to the document object when executed in the console. Now, I want to set up an Express server to run the script whenever ...

Numbering the items in ng-repeat directive

I am facing a challenge with my AngularJS directive that is recursively nested within itself multiple times. The issue lies in the fact that the names of items in ng-repeat conflict with those in the outer element, causing it to malfunction. To illustrate ...

Retrieve the JSON array embedded within the JSON string

Can someone help me extract the JSON array from a JSON string? I've been struggling to make it work. Here is the code snippet for reference: // I need assistance with this var all_barcodes = '{"VAM12345":{"colour":"red","size":"32"},"VAM456789" ...

Issue encountered while invoking the jQuery html method

Embarking on my first adventure with javascript + jQuery, creating a basic page but running into errors. I've gone through the code multiple times and still can't seem to find the issue. Below is the error message I am encountering: The complet ...

Ruby on Rails: clearing the asset pipeline cache by hand

While Rails usually clears the asset pipeline cache automatically when files are modified, I am facing a unique situation. I am providing my application as an HTML response to an Ajax request, cross-domain using rack-cors to bypass CORS. The issue arises ...

What exactly constitutes a circular data structure within JSON?

I'm encountering an issue in my Express app where I am receiving the following error: UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON Despite searching for similar problems, I am struggling to grasp the concept o ...

"Trying to upload a PDF file with ajax, but encountering consistent failures with

I've been struggling with this code that just won't work as intended. I'm attempting to send file data and an ID to the php side, but it's failing consistently. I can't figure out what mistake I'm making. Any help would be gre ...

Is the variable empty outside of the subscribe block after it's been assigned?

Why is a variable assigned inside subscribe empty outside subscribe? I understand that subscribe is asynchronous, but I'm not sure how to use await to render this variable. Can someone please help me and provide an explanation? I am attempting to retr ...

What is the process for the event loop moving into the poll phase?

There is a scenario outlined in the event loop explanation on the Node.js official website. When setTimeout is triggered, and the callback queue for the timer phase isn't empty, why does the event loop move on to the poll phase? The site mentions that ...

How to send an html form with php, store it in a MySQL Database, and utilize Ajax and jQuery for

As a beginner in PHP form creation, I have been exploring various tutorials and combining different techniques to create my form. However, I am facing challenges as none of the tutorials cover everything comprehensively from beginning to end. While I beli ...

Utilizing Angular's asynchronous validators to handle incoming response data

Struggling with async validators in Angular and trying to implement Container/Presentational Components architecture. Created an async validator to check for the existence of an article number, with the service returning detailed information about the arti ...

Transform an array containing strings into an array containing objects

I'm working with an array that consists of strings containing geographical data. https://i.sstatic.net/4xQWL.png Is there a way to convert this array into an array of objects with the following structure: obj[0] = {lat:0, lng:0} ...

When additional lines are drawn elsewhere on the HTML5 Canvas, the diagonal lines will gradually appear thicker and more pronounced

For horizontal and vertical lines, using a translation of 0.5 for odd stroke widths results in crisper and sharper lines. But what about diagonal lines? Link to jsfiddle <!DOCTYPE html> <html lang="en"> <body style="background: black"& ...

The <iframe> generated by Create-React-App often hinders my ability to interact with or modify the application directly, requiring me to remove it using the browser's element editor

After conducting a global installation of create-react-app, I encountered an issue where instead of editing the rendered content directly in the browser while working on a project, there is a mysterious container created around my app. Upon closer examina ...

Examining Angular Modules using Jasmine Unit Tests

Currently, I am integrating an AngularJS service into my application. Upon testing, I discovered that the service is not as reliable as I had hoped. To address this issue, I decided to implement some unit tests for it. While the service functions properly ...