New to JavaScript – Why Doesn’t My Program Show Output in VS Code?

•Hi, I’m learning JavaScript and using VS Code. I’ve written a simple program, but when I run it in the terminal, I only see [done] and exited with code=0 in 0.2 seconds.

  • I’m not getting any output, and I’m not sure why. Is this normal?

  • I’ve read about using console.log(), but I’m hoping there’s a way to get output displayed directly in the Output section without needing console.log().

    with console.log
    without console.log

  • I’m expecting the program to output some text or perform an action that would be noticeable.

  • Is this normal behavior for JavaScript programs in VS Code? Or am I missing something that’s preventing my program from running as intended?

Use $t function of i18n in pure js on vue

I´m trying use the $t() function of i18n in a pure JS file on Vue. I separate i18n related codes in main.js and make a .js file, then I import the i18n variable in a pure js file and when I try use a translation show this error TypeError: i18n.t is not a function.
this is my code in i18n.js file

import en from '../locales/en.json'
import es from '../locales/es.json'
import { createI18n } from 'vue-i18n'

const languajes = {
  en: en,
  es: es
}

var i18n = createI18n({
  locale: 'es',
  messages: languajes
});

export default i18n;

and in my pure js file I have this

import i18n from "./i18n";

export default {
...
badge(status){

    switch (status) {
        case 1:
            return  `<span class="badge text-bg-primary">${ i18n.t('modules.clients.status.approved') }</span>`;
            break;
    
        default:
            break;
    }

 }
...
}

how I can use the t() function in my js file?

Session management problem in Next JS where the session is not being available in a sub-domain

I am trying to solve a problem where I have a website, and upon logging in or using sign-up, a session is created in the root domain (For example: localhost:3000) where my application is running. Now, ideally my website is tenants based so for each tenant, there is a different subdomain to be used with the root domain (For example: app.localhost:3000). Now, the session is being created perfectly in the root domain but upon logging in, when I redirect to the sub-domain, the session returns empty there. I have tried everything, I don’t know what I am doing wrong.

Here is the “/api/auth[…nextauth]/route.ts” file which is creating the said session using CredentialsProvider.

import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import prisma from "../../../../lib/prisma"
import { compare } from "bcrypt"

export const authOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    CredentialsProvider({
      name: "Custom",
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        console.log("Attempting to authorize user:", credentials?.email)

        if (!credentials?.email || !credentials?.password) {
          console.log("Missing email or password")
          return null
        }

        const user = await prisma.user.findUnique({
          where: { email: credentials.email }
        })

        if (!user) {
          console.log("User not found")
          return null
        }

        if (!user.passwordHash) {
          console.log("User has no password hash")
          return null
        }

        const isPasswordValid = await compare(credentials.password, user.passwordHash)

        if (!isPasswordValid) {
          if (credentials.password === user.passwordHash) {
            console.log("User authorized successfully")
            return {
              id: user.id.toString(),
              email: user.email,
              name: `${user.firstName} ${user.lastName}`,
            }
          }
          console.log("Invalid password")
          return null
        }

        console.log("User authorized successfully")
        return {
          id: user.id.toString(),
          email: user.email,
          name: `${user.firstName} ${user.lastName}`,
        }
      }
    })
  ],
  session: {
    strategy: "jwt",
    maxAge: 60 * 60,
  },
  jwt: {
    maxAge: 60 * 60, // 1 hour in seconds
  },
  callbacks: {
    async jwt({ token, user }: {
      token: { id: string },
      user: { id: string }
    }) {
      if (user) {
        token.id = user.id
      }
      return token
    },
    async session({ session, token }: {
      session: any,
      token: { id: string }
    }) {
      if (session?.user) {
        session.user.id = token.id
      }
      return session
    }
  },
  pages: {
    signIn: "/sign-in",
    newUser: "/sign-up"
  },
  debug: true, // Enable debug messages in the console
  cookies: {
    sessionToken: {
      name: `next-auth.session-token`,
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        secure: false,
        domain: '.localhost'
      }
    }
  },
  
  // Simplified CORS configuration for localhost
  cors: {
    origin: [
      'http://localhost:3000',
      'http://app.localhost:3000',
      'http://app1.localhost:3000',
      'http://app2.localhost:3000',
      'http://farhan-dev.localhost:3000'
    ],
    credentials: true,
  }
}

const handler = NextAuth(authOptions)

export { handler as GET, handler as POST }

Please let me know if you guys need anything else at all from my project. I’ll gladly provide it to you to solve this problem. Any help is appreciated! Thanks!

i want to understand why this comparison isn’t working in javascript

i have an if statement in JavaScript, the problem (was its fixed now but I don’t know why)
when the parameters are val1 and val2 as objects, this Code works:

if (typeof(val1) === typeof(val2) === 'object' && val1 !== null && val2 !== null) 

but this Code does :

 if (typeof(val1) === 'object' && typeof(val2) === 'object' && val1 !== null && val2 !== null)

How is

typeof(val1) === 'object' && typeof(val2) === 'object' 

difrente from :

typeof(val1) === typeof(val2) === 'object'

i treid to ask chat gpt this is the answer and it worked but i want to know why

It looks like the issue is with how the comparisons are structured. The expression typeof(val1) === typeof(val2) === ‘object’ doesn’t work as intended because it evaluates left to right. Instead, try breaking it down like this:

if (typeof(val1) === 'object' && typeof(val2) === 'object' && val1 !== null && val2 !== null) {

Dropdown Data Not Displaying

I have a drop down that renders blank when clicked but when the page is resized or it is scrolled, then the data appears. It is attempting to load 2700 elements. I have another drop down that displays correctly but there is only 70 elements in that one. I get this warning when scrolled: “This site appears to use a scroll-linked positioning effect. This may not work well with asynchronous panning; see https://firefox-source-docs.mozilla.org/performance/scroll-linked_effects.html for further details and to join the discussion on related tools and features!” It seems like the bug is due to the number of elements that are attempting to display.

<div class="form-group col-md-2 col-sm-3 col-xs-4" style="margin-left:20px;">
                        <label>Provider (Total: <span id="provider-count"></span>):</label></br>
                        <select multiple id="doctorsDropdown" class="selectpicker" required data-live-search="true"
                            data-live-search-style="startsWith" data-actions-box="false" data-live-search-placeholder="Search">
                        </select>
                    </div>

function updateDataTable() 
        {
            var selectedDoctors = $('#doctorsDropdown').val();
            var selectedSpecialties = $('#specialtyDropdown').val();

            function appendParam(key, value) {
                if (value !== null && value !== undefined) {
                    params.push(key + '=' + encodeURIComponent(value));
                }
            }

            var params = [];

            appendParam('doctors', selectedDoctors);
            appendParam('specialities', selectedSpecialties);

            var baseURL = './provider_report_data?' + params.join('&');

            if ($.fn.DataTable.isDataTable('#dc-table-chart')) {
                $('#dc-table-chart').DataTable().clear().destroy();
            }
            initializeFirstTable(baseURL);
        }

$.ajax({
            url: './get_data_of_providers',
            method: 'GET',
            success: function (data) {
                const formattedData = data.map(item => {
                    const nameParts = item.full_name.split(' ');
                    const lastName = nameParts.pop();
                    const firstName = nameParts.join(' ');
                    return {
                        ...item,
                        full_name: lastName + ', ' + firstName,
                        last_name: lastName
                    };
                });

                formattedData.sort((a, b) => a.last_name.localeCompare(b.last_name));

                $('#doctorsDropdown').empty();
                $('#doctorsDropdown').append($('<optgroup>', {}).append($('<option>', {
                    value: '',
                    text: 'Deselect All'
                })));

                var fragment = document.createDocumentFragment();
                formattedData.forEach(function (item) {
                    var doctorName = item.full_name;
                    if ('{{sensitiveMode}}' === 'true' && providerMapping[doctorName]) {
                        doctorName = providerMapping[doctorName].fakeName;
                    }
                    var option = $('<option>', {
                        value: item.full_name,
                        text: doctorName
                    });
                    fragment.appendChild(option[0]);
                });

                $('#doctorsDropdown').append(fragment);
                $('#doctorsDropdown').selectpicker('refresh');
                
                // Optionally trigger resize if necessary
                $(window).trigger('resize');
            },
            error: function (error) {
                console.error('Error loading doctor details:', error);
            }
        });

$('#doctorsDropdown').on('change', function () {
            const containerId = $(this).attr('id');
            deselectAllOptions(containerId);
            updateDataTable();
});

I have tried to automatically scroll or resize the page but that is a band-aid instead of a fix.

Picture of the unrendered dropdown

How do I connect a node.js API to a RabbitMQ instance on Fly.io?

See more: JavascriptNode.jsRabbitMQ
I have a project that I am trying to get connected to a rabbit mq broker that I have set up on fly.io with a node.js API, but I cannot figure out how to do this.

What I have tried:

I tried various ways of re-writing the url for the amqp connection, but none of these worked. Here is my rabbit mq url environment variable within my node.js api:

#----Service Dependency Variables----
RABIT_MQ_URL=amqp://rabbit-mq-fly-dep.fly.dev:5672
#----Service Dependency Variables----

I also tried this format:

#----Service Dependency Variables----
RABIT_MQ_URL=amqp://USERNAME:[email protected]:5672/VHOST_NAME
#----Service Dependency Variables----

however, the error that I got in my node.js app is still the same:

ERR {
  success: false,
  message: Error: getaddrinfo ENOTFOUND rabbit-mq-fly-dep.fly.dev
      at GetAddrInfoReqWrap.onlookupall [as oncomplete] (node:dns:120:26) {
    errno: -3008,
    code: 'ENOTFOUND',
    syscall: 'getaddrinfo',
    hostname: 'rabbit-mq-fly-dep.fly.dev'
  }
}

I have been looking online at other resources, but I can’t find anything that could help me. The docs didn’t seem to be much help either unless you want to connect to a local host which is easy:

#---Service Dependency Variables----
RABIT_MQ_URL=amqp://locahost
#----Service Dependency Variables----

This works every time if I run a rabbit MQ instance locally, of course.

I should also address that I did try and add an IP address to the fly.io deployment and tweaked the url to use amqps insted of the amqp protocol in the node API’s environment variables since the rabbit mq instance is set up to use TLS, but still got the same connection error. Here is the format of said implementation in the node.js API’s variables:

#----Service Dependency Variables----
RABIT_MQ_URL=amqps://USERNAME:PASSWORD@IPV6ADDRESS:5672/emailer
#----Service Dependency Variables----

I have no idea why this isn’t working.

Here is my docker file for the fly.io rabbit mq instance:

FROM rabbitmq:3-management-alpine
COPY ./prod.conf /etc/rabbitmq/rabbitmq.conf
RUN rabbitmq-plugins enable rabbitmq_management

and my fly.io toml file:

# fly.toml app configuration file generated for rabbit-mq-fly-dep on 2024-09-25T14:16:38-04:00
#
# See https://fly.io/docs/reference/configuration/ for information about how to use this file.
#

app = 'rabbit-mq-fly-dep'
primary_region = 'mia'

[build]

[[services]]
  protocol = "tcp"
  internal_port = 5672

  [[services.tcp_checks]]
    interval = "15s"
    timeout = "1m0s"
    grace_period = "1s"

  [[services.ports]]
    port = 5673
    handlers = ["tls"]

[[services]]
  protocol = "tcp"
  internal_port = 15672

  [[services.ports]]
    port = 15672
    handlers = ["tls", "http"]

  [[services.tcp_checks]]
    interval = "15s"
    timeout = "1m0s"
    grace_period = "1s"

and here is the rabbit mq instance’s .config file

listeners.tcp.default=5672
default_user=admin
default_pass=admin
management.tcp.ip=::

Any help on how to get this working would be much appreciated. Thanks!

Implemntar v-autocomplete

I am trying to implement v-autocomplete, which is basically a searchable select, but I’m not able to pass the customer names data. In the browser console, it shows that the data is invalid. I feel like it’s something simple, but I’ve been stuck on this for a week now.

Here is my code:

`<template>
  <v-container class="d-flex align-center justify-center">
    <v-form @submit.prevent="createLicense" ref="form">
      <!-- Select para Cliente -->
      <v-autocomplete
        v-model="selectedClient"
        :items="clients"
        item-text="Nome"  
        item-value="Id"   
        label="Selecione o Cliente"
        :loading="loadingClients"
        no-data-text="Nenhum cliente encontrado"
        outlined
        dense
      ></v-autocomplete>

      <!-- Select para Sistema -->
      <v-autocomplete
        v-model="selectedSystem"
        :items="systems"
        item-text="Nome"  
        item-value="Id"   
        label="Selecione o Sistema"
        :loading="loadingSystems"
        no-data-text="Nenhum sistema encontrado"
        outlined
        dense
      ></v-autocomplete>

      <!-- Campo de data de validade -->
      <v-text-field 
        v-model="dataValidade" 
        label="Data de Validade" 
        type="date"
        :rules="[v => !!v || 'Data é obrigatória']" 
        required 
        outlined 
        dense
      ></v-text-field>

      <!-- Campo para quantidade de usuários limitados -->
      <v-text-field 
        v-model="qtdeUsuariosLimitados" 
        label="Quantidade de Usuários Limitados" 
        type="number"
        :rules="[v => v >= 0 || 'Deve ser positivo']" 
        required 
        outlined 
        dense
      ></v-text-field>

      <!-- Campo para quantidade de usuários ilimitados -->
      <v-text-field 
        v-model="qtdeUsuariosIlimitados" 
        label="Quantidade de Usuários Ilimitados" 
        type="number"
        :rules="[v => v >= 0 || 'Deve ser positivo']" 
        required 
        outlined 
        dense
      ></v-text-field>

      <!-- Botão de submissão -->
      <v-btn type="submit" color="primary" class="mt-4" large>Cadastrar Licença</v-btn>
    </v-form>
  </v-container>
</template>

<script>
import LicenseService from '@/services/Licenses/licenses';
import ClientService from '@/services/Clients/clients';
import SystemService from '@/services/Systems/systems';

export default {
  data() {
    return {
      clients: [],
      systems: [],
      selectedClient: null,
      selectedSystem: null,
      loadingClients: false,
      loadingSystems: false,
      dataValidade: '',
      qtdeUsuariosLimitados: '',
      qtdeUsuariosIlimitados: '',
    };
  },
  methods: {
    async getClients() {
      this.loadingClients = true;
      try {
        const response = await ClientService.getAllClients();
        this.clients = response.value.map(({ $id, ...rest }) => rest); // Remove o campo desnecessário
      } catch (error) {
        this.$toast.error('Erro ao buscar clientes');
      } finally {
        this.loadingClients = false;
      }
    },
    async getSystems() {
      this.loadingSystems = true;
      try {
        const response = await SystemService.getAllSystems();
        this.systems = response.value;
      } catch (error) {
        this.$toast.error('Erro ao buscar sistemas');
      } finally {
        this.loadingSystems = false;
      }
    },
    async createLicense() {
      if (!this.$refs.form.validate()) {
        return;
      }

      if (!this.selectedClient || !this.selectedSystem) {
        this.$toast.error('Selecione um cliente e um sistema.');
        return;
      }

      try {
        const selectedClient = this.clients.find(client => client.Id === this.selectedClient);
        const selectedSystem = this.systems.find(system => system.Id === this.selectedSystem);

        const licenseData = {
          Id: 0,
          Cliente: {
            Id: selectedClient.Id,
            Chave: selectedClient.Chave,
            Nome: selectedClient.Nome,
            Email: selectedClient.Email,
            Telefone: selectedClient.Telefone
          },
          Sistema: {
            Id: selectedSystem.Id,
            Nome: selectedSystem.Nome
          },
          Ativa: true,
          DataValidade: this.dataValidade,
          QtdeUsuariosLimitados: this.qtdeUsuariosLimitados,
          QtdeUsuariosIlimitados: this.qtdeUsuariosIlimitados
        };

        await LicenseService.createLicense(licenseData);
        this.$router.push({ name: 'LicenseList' });
        this.$toast.success('Licença criada com sucesso!');
      } catch (error) {
        this.$toast.error('Erro ao criar licença!');
      }
    }
  },
  created() {
    this.getClients();
    this.getSystems();
  }
};
</script>


<style scoped></style>`

And this is what the request returns: Request for sistemas:

`{
    "value": [
        {
            "$id": 1,
            "Id": 8,
            "Nome": "Sistema1"
        },
        {
            "$id": 2,
            "Id": 9,
            "Nome": "Sistema2"
        },
        {
            "$id": 3,
            "Id": 10,
            "Nome": "sistema3"
        }
    ]
}`

Request for clientes:

`{
    "value": [
        {
            "$id": 1,
            "Id": 2,
            "Chave": "042176ec-7a2c-499e-881a-496a2c14fa64",
            "Nome": "cliente",
            "Email": "[email protected]",
            "Telefone": "99999999"
        },
        {
            "$id": 2,
            "Id": 3,
            "Chave": "ce8fc289-1e68-48e3-9468-4ec1d02ab205",
            "Nome": "cliente2",
            "Email": "[email protected]",
            "Telefone": "99999999"
        },
        {
            "$id": 3,
            "Id": 4,
            "Chave": "5d48b749-f724-4479-ad69-e1d408fa677c",
            "Nome": "Cliente3",
            "Email": "[email protected]",
            "Telefone": "999999999"
        },
        {
            "$id": 4,
            "Id": 5,
            "Chave": "0d595f88-a350-48dd-a014-d5826459b4f0",
            "Nome": "Cliente4",
            "Email": "[email protected]",
            "Telefone": "999999999"
        }
    ]
}`

Access HTML tag rules from jQuery

My question is if there is a way to access the content of HTML <style> element from jQuery.

<style>
.calendarNavbarLink {
    margin-left: 20px;
}

.today {
    background-color: lawngreen;
}

.weekend {
    background-color: lightsalmon;
}
</style>

For example: I would access the value of the property background-color of the rule .weekend. Is it possible do this from jQuery?

Cannot do npm run

I have a ReactJS project, with package.json file:

{
  "name": "front-end",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "bootstrap": "^5.3.2",
    "cors": "^2.8.5",
    "pg-promise": "^11.5.4",
    "querystring": "^0.2.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-resizable": "^3.0.5",
    "react-router-dom": "^6.16.0",
    "react-scripts": "5.0.1",
    "react-split-pane": "^0.1.92",
    "web-vitals": "^2.1.4",
    "zlib": "^1.0.5"
  },
  "devDependencies": {
    "nodemon": "^2.0.22"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "dev": "nodemon server.js"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Whenever I do npm install it does not work therefore I add –force flag and I get:

npm error path C:UsersMASTERDatabaseViewerAppfront-endnode_moduleszlib
npm error command failed
npm error command C:Windowssystem32cmd.exe /d /s /c node-waf clean || true; node-waf configure build
npm error System cannot find the path specified
npm error 'true' is not recognized as an internal or external command,
npm error operable program or batch file.
npm error A complete log of this run can be found in: C:UsersMASTERAppDataLocalnpm-cache_logs2024-09-26T18_02_42_496Z-debug-0.log

When I do npn run dev I can see that some libraries cannot be resolved:
Module not found: Error: Can’t resolve ‘react-router-dom’ in ‘C:UsersMASTERDatabaseViewerAppfront-endsrc’

Even when I try to install this module with –force it still occurs.

Returning an error from server action Next.js

This is my server action.

I use Drizzle for communication with my db.

Below is the simple delete User function which works fine.

'use server'

export async function deleteUser(id: number) {
  try {
    await db.delete(users).where(eq(users.id, id));
    revalidatePath("/");
  } catch (error) {
    console.log(error);
    return NextResponse.json({
      message: error instanceof Error ? error.message : "Unknown error",
    });
  }
}

And this is my client function where I invoke server action:

'use client' 

const deleteUserHandler = async (id: number) => {
    try {
      await deleteUser(id);
      toast.success(`${user.name} deleted successfully!`);
    } catch (error) {
      console.log(error);
      toast.error("An Error Occurred!");
    }
  };

For example, when I force Offline mode in Network tab I am getting this message in browser console:

TypeError: Failed to fetch
    at fetchServerAction (server-action-reducer.js:32:23)

I don’t even get error in my terminal console inside VSC.

Can somebody explain to me how can I for example throw custom message inside the server action and display that message as alert for example in my client component?

How to create function with parameters on java script, get error [closed]

I try to create function “grate(from, to)”, to get rate with parametres, but i return error, please help me.

    <script>
function grate(from, to){
var burl = 'https://bitpay.com/rates/'
    var symbol1 = 'from'
    var symbol2 = 'to'
    var symbol = '/'
    var url = burl + symbol1 + symbol + symbol2
    var ourRequest = new XMLHttpRequest()
    
    ourRequest.open('GET', url, true)
    ourRequest.onload = function(){
    
    
    var str =  ourRequest.responseText
      var strobj = JSON.parse(str)
     return document.body.innerHTML = strobj.data.rate
    }
   ourRequest.send()

}
grate(btc, usd)
</script>

Visual Studio Code: Enable “Go to Definition” for JavaScript

Good Day!

I need to enable the “Go to Definition (F12)” in Visual Studio Code, for example, right click on fix_android function and press Go to Definition should move cursor to the function’s line $.bebo.bootstrap.fix_android = function () { .. right now it doesn’t work, Is there a setting should be set?

(function ($) {
'use strict';

$.bebo = $.bebo || {};
// Fixes
$.bebo.bootstrap = $.bebo.bootstrap || {};


$.bebo.global_vars = {
    window: null,
};

$(document).ready(function () {

    $.bebo.global_vars.window = $(window);

    // Press (F12) on fix_android should go down to the function
    $.bebo.bootstrap.fix_android();
    $.bebo.bootstrap.Initialize();
});


$.bebo.bootstrap.fix_android = function () {
    /* Do SOME */
}

$.bebo.bootstrap.Initialize = function () {
    /* Do SOME */
}

})(jQuery);