How to access property ‘switch’ in an object in javascript? [duplicate]

In my home automation (nodered) there is a device that is sending it’s actual state. Within this state there is a property ‘switch’. I.e.: myDevice.state.switch.
‘switch’ is a key word in javascript, so I cannot access it in the normal way. Furthermore I’m not able to change the property’s name, because it is implemented in the device.

As a work around I can access this property by accessing it as an array element, similar to ‘Object.elements(myDevice.state)[1][1])’. This gives me the expected value.

I also can access the property ‘switch’ as a string this way, but I’m not able to change this string in order to change the property’s name.

But is this the only way to access such a (stupid) property? The access MUST be possible without using ‘switch’.

How to dynamically fetch nested json arrays keys and properties without explicitly mentioning the fields?

I have a requirement to create a nested JSON to create an issue in JIRA.

The thing is this will work for only content.content.text path. If new keys and values are added in the future, this means it will not work. I’ve tried to automate it by fetching the keys and values in the payload.

However if you look at the following snippet, you’ll see that ‘text’ is explicitly mentioned so it could create a problem in the future. I’m trying to find a way to replace the ‘text’ to be automatically fetched instead of explicitly defining the key?

 Object.keys(newItem).forEach(k => newItem[k] = (k === 'text') ? value : newItem[k]);

So how can I find it?

function assignNestedValue(obj, path, value) {
    const parts = path.split('.');
    let current = obj;

    for (let i = 0; i < parts.length; i++) {
        const part = parts[i];

        // Handle array dynamically without explicit "type" or "text"
        if (Array.isArray(current[part])) {
            if (i === parts.length - 2) {
                const lastItem = current[part][current[part].length - 1];

                // If last item has any empty string, assign value to that key
                const emptyKey = Object.keys(lastItem).find(k => lastItem[k] === "");
                if (emptyKey) {
                    lastItem[emptyKey] = value;
                } else {
                    // If no empty field, clone the structure dynamically and assign value
                    const newItem = { ...lastItem };  // Copy existing structure
                    Object.keys(newItem).forEach(k => newItem[k] = (k === 'text') ? value : newItem[k]);
                    current[part].push(newItem); // Push the new item
                }
                return;
            }

            current = current[part][current[part].length - 1]; // Move to the last item in the array
        } else if (typeof current[part] === 'undefined') {
            // Create the path if it doesn't exist
            current[part] = {};
            current = current[part];
        } else if (i === parts.length - 1) {
            current[part] = value; // Assign value to the last part
        } else {
            current = current[part];
        }
    }
}

// Example usage of the function
var jiraPayload = {
    fields: {
        project: {
            key: ""
        },
        description: {
            type: "doc",
            version: 1,
            content: [
                {
                    type: "paragraph",
                    content: [
                        {
                            type: "text",
                            text: ""
                        }
                    ]
                }
            ]
        },
        issuetype: {
            id: "10007"
        },
        priority: {
            id: "1"
        },
        summary: ""
    }
};

// Dynamically assign values

assignNestedValue(jiraPayload.fields, "description.content.content.text", "This is the new payload description");
assignNestedValue(jiraPayload.fields, "description.content.content.text", "This is the second description");
assignNestedValue(jiraPayload.fields, "description.content.content.text", "This is the third description");
assignNestedValue(jiraPayload.fields, "description.content.content.text", "This is the fourth description");
assignNestedValue(jiraPayload.fields, "summary", "uploading json");
assignNestedValue(jiraPayload.fields, "project.key", "SI");

console.log(JSON.stringify(jiraPayload, null, 2));

the output is also working as expected

{
  "fields": {
    "project": {
      "key": "SI"
    },
    "description": {
      "type": "doc",
      "version": 1,
      "content": [
        {
          "type": "paragraph",
          "content": [
            {
              "type": "text",
              "text": "This is the new payload description"
            },
            {
              "type": "text",
              "text": "This is the second description"
            },
            {
              "type": "text",
              "text": "This is the third description"
            },
            {
              "type": "text",
              "text": "This is the fourth description"
            }
          ]
        }
      ]
    },
    "issuetype": {
      "id": "10007"
    },
    "priority": {
      "id": "1"
    },
    "summary": "uploading json"
  }
}

How can a mid-level developer evaluate their skills and identify areas for growth? [closed]

I’m currently working as a mid-level frontend developer with React and TypeScript. However, compared to other mid-level developers, I sometimes feel like I’m not quite on the same level as I’d like to be. I want to improve, but it’s not always clear where to focus my efforts.

In your experience, what distinguishes strong mid-level developers? What should I focus on to keep growing? For example: diving deeper into app architecture, improving TypeScript knowledge, working on performance, gaining experience with GraphQL and Apollo, or something else?

I’d appreciate any advice or recommendations!

I have been reading up on app architecture and improving my TypeScript skills. However, I still feel like my progress isn’t as noticeable as I’d hoped. I was expecting to feel more confident in my abilities compared to other mid-level developers but I’m unsure if I’m focusing on the right areas.

How to get the first dropdown answer’s value dynamically?

question

I have defined a custom question type, which name is cascadedropdown,the code is as follows:

ComponentCollection.Instance.add({
  // A unique name; must use lowercase
  name: 'cascadedropdown', // A display name used in the Toolbox
  title: 'cascade dropdown', // A default title for questions created with this question type
  defaultQuestionTitle: 'choose the options',
  elementsJSON: [
    {
      type: 'dropdown',
      name: 'dropdown1',
      title: 'question1',
      choices: [
        {
          text:"apple",
          value:1,
        },
        {
          text:"orange",
          value:2,
        }
      ], 
    },
    {
      type: 'dropdown',
      name: 'dropdown2',
      title: 'question2',
      startWithNewLine: false,
      choices:getSecondLevelChoices(1)
    },
    {
      type: 'dropdown',
      name: 'dropdown3',
      title: 'question3',
      startWithNewLine: false,
      choices:[],
      visible: casecadeQuestionList.length > 2
    },
    {
      type: 'dropdown',
      name: 'dropdown4',
      title: '问题4',
      startWithNewLine: false,
      choices:[],
      visible: casecadeQuestionList.length > 3
    },
  ],
  inheritBaseProps: true
})

on the code above, there are at least two dropdowns in the casecadedropdown question, the second dropdown question’s choices depend on the first dropdown answer. the method getSecondLevelChoices(1), the parameter 1 is the first dropdown answer’s value.

The question is how to get the first dropdown answer’s value dynamically.

the template is

<SurveyCreatorComponent :model="creator" />

Javascript GZIP Compressed string is invalid when read by .NET Deflate stream and GZipStream

So, try as I might, I’m having issues decompressing a string in .NET.

The string is being compressed in Javascript with the following:

const compressedFileText = await compressArrayBuffer(await readFileIntoArrayBuffer(selectedFile));

selectedFile is an object defined as

class selectedFile {
    readonly file: File;
    constructor(file: File) {

    }
    // remainder omitted...
}

The other functions involved here are:

async function compressArrayBuffer(arrBuffer: ArrayBuffer): Promise<string> {

    const stream = new Blob([arrBuffer]).stream();
    const compressedReadableStream = stream.pipeThrough(new CompressionStream("gzip"));
    const compressedResponse = await new Response(compressedReadableStream);
    const blob = await compressedResponse.blob();

    tempDownloadFunction(blob);

    const buffer = await blob.arrayBuffer();
    const bufferView = new Uint8Array(buffer);
    const compressedString = new TextDecoder().decode(bufferView);
    return compressedString;
}

function tempDownloadFunction(blob: Blob): void {
    const elem = window.document.createElement("a");
    elem.href = window.URL.createObjectURL(blob);
    elem.download = '';
    document.body.appendChild(elem);
    elem.click();
    document.body.removeChild(elem);
}

async function readFileIntoArrayBuffer(selectedFile: SelectedFile): Promise<ArrayBuffer> {

    return new Promise<ArrayBuffer>((resolve, reject) => {

        const reader = new FileReader();
        reader.onload = () => {

            resolve(reader.result as ArrayBuffer);
        }
        reader.onerror = reject;
        reader.readAsArrayBuffer(selectedFile.file);
    });
}

This all works fine, and the compressed string is sent to the server as part of a JSON object.

However, when try to decompress on the server I get an Exception with the message:

System.IO.Compression: “The archive entry was compressed using an unsupported compression method.”

I’ve tried decompressing via DeflateStream and GZipStream as below:

public static string Decompress(string compressedString)
{
    byte[] decompressedBytes;

    byte[] buffer = Encoding.UTF8.GetBytes(compressedString);

    var compressedStream = new MemoryStream(buffer);

    using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
    {
        using (var decompressedStream = new MemoryStream())
        {
            decompressorStream.CopyTo(decompressedStream);

            decompressedBytes = decompressedStream.ToArray();
        }
    }

    return Encoding.UTF8.GetString(decompressedBytes);
}

and…

public static string UnZip(string value)
{
    //Transform string into byte[]
    byte[] byteArray = new byte[value.Length];
    int indexBA = 0;
    foreach (char item in value.ToCharArray())
    {
        byteArray[indexBA++] = (byte)item;
    }

    //Prepare for decompress
    System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray);
    System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(ms,
        System.IO.Compression.CompressionMode.Decompress);

    //Reset variable to collect uncompressed result
    byteArray = new byte[byteArray.Length];

    //Decompress
    int rByte = sr.Read(byteArray, 0, byteArray.Length);

    //Transform byte[] unzip data to string
    System.Text.StringBuilder sB = new System.Text.StringBuilder(rByte);
    
    for (int i = 0; i < rByte; i++)
    {
        sB.Append((char)byteArray[i]);
    }
    sr.Close();
    ms.Close();
    sr.Dispose();
    ms.Dispose();
    return sB.ToString();
}

I’m not sure what I’m doing wrong, and no searching that I’ve tried has yielded a result. However, taking the compressed string downloaded via the temp function and running it through WinZip correctly decompresses it and yields my input file with all data intact.

Can anyone help, please?

How to use image ressource from sitepackage in javascript file in TYPO3 12?

Within a TYPO3 12 website I use the Sitepackagebuilder to create a sitepackage.

The Resources are structured as following:

Resources
  ...
  Public
    JavaScript
      scripts.js
    Icons
      arrow.png
    ...

Within my scripts.js I would like to access an icon from the Icons-folder (arrow.png) to use it with the slick slider as follows:

 $slider.slick({
   infinite: true,
   slidesToShow: 3,
   arrows: true,

   // Does not work due to script compression:
   prevArrow: "<button class='slick-prev slick-arrow' aria-label='Previous' type='button'><img src='../Icons/arrow.png'></button>",

   // I would like to access it like this (but it does not work):
   prevArrow: "<button class='slick-prev slick-arrow' aria-label='Previous' type='button'><img src='EXT:sitepackage/Resources/Public/Icons/slider-left.png'></button>",

   // Using the icon from fileadmin does work:
   prevArrow: "<button class='slick-prev slick-arrow' aria-label='Previous' type='button'><img src='fileadmin/Icons/slider-left.png'></button>",
 });

Does anybody know how to use an image ressources from the sitepackage within javascript in TYPO3?

Is there a native javascript API to manipulate the undo stack of HTML elements?

I created a contenteditable element in my page and during some events I update it by replacing the innerHTML. When I do that, the undo stack gets reset.

I found some recommendations to use the executeCommand api, but the MDN doc says it’s deprecated and does not offer an alternative.

  • Is there a way to update the innerHTML while keeping the undo stack intact?
  • Alternatively, is there a way to manipulate the undo stack of an element using javascript?

Load Local WebSite Folder from Document Directory

I am trying to load Website Folder from the Document Directory. It’s a PWA Bundle. When i load the Folder from the Bundle, It loads in WkWebview. But when i try to load it from Document Directory, it’s not loading from the folder. May files are missing including main.js, though all those files are there in the bundle(i double checked).

Below is the Sample Code which is not loading.

var url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("DownloadedHTMLNew").appendingPathComponent("index.html")
self.webView?.loadFileURL(url, allowingReadAccessTo: url)

Below is the code which is loading from bundle directory.

if let value = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "DownloadedHTMLNew") {
let url = URL(fileURLWithPath: value)
self.webView?.loadFileURL(url, allowingReadAccessTo: url)
}

Let me know your suggestions.

Nothing appears in browser console while inspecting element while executing dynamic action in oracle apex

Problem: When I examine the element in the browser console, it does not return any details about the procedure as it was before.
I don’t know if the latest update of Chrome browser is the reason. If anyone has any details about the subject, I am very grateful and thankful.

item 1 : P2_ITEM1

item 2 : P2_ITEM2

Dynamic action:Execute JavaScript

Code : $s(‘P2_ITEM1’),$v(‘P2_ITEM2’);

The dynamic action is executed correctly. The problem occurs when examining the element in the console. Nothing appears, as in the image.
enter image description here
While it was expected as in the following picture
enter image description here

How to change width and height of iframe tag dynamically?

My <iframe> tag contains a chat widget; that chat widget contains a button that shows and hide chat inbox. How do I modify it so that it changes its width and height according to if the inbox is visible or not?

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
   
    <title>Parent Page</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="box">
      <p style="color: white; font-size: 50px">This is the HTML page</p>
    </div>

    <iframe src="http://localhost:5010/widget" id="target"></iframe>
  </body>
</html>

CSS

.box {
  width: 500px;
  height: 500px;
  background-color: brown;
}

#target {
  position: fixed;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background-color: red;
  border: none;
  width: 350px;
  height: 100%;
}

Here is the screen shot of chat widget – click here

I tried using this way but it doesn’t work

window.addEventListener("message", function (event) {
        console.log("message event fired");

        const iframe = document.getElementById("target");
        const { width, height } = event.data;

        if (width && height) {
          iframe.style.width = width + "px";
          iframe.style.height = height + "px";
        }
      });

Kendo Grid White Space Issue on Scroll in Firefox after Adding “Back to Top” Feature

  1. I’m facing an issue with the Kendo Grid where white spaces appear when scrolling in Firefox. The grid works fine in other browsers. This issue started occurring after I implemented a “Back to Top” feature. It seems that the grid is unable to calculate its height dynamically during scrolling, which leads to rendering issues. Below is the relevant part of my code:
  <kendo-dialog [title]="openProjectDialog ? 'All Projects' : 'Ticket List'" 
                (close)="onClose()"
                [width]="'80%'" 
                [height]="'80%'" 
                class="overlapPopup">
    
    <!-- Marquee Text Section -->
    <div class="marquee-wrapper" *ngIf="fullMarqueeText">
      <marquee behavior="scroll" direction="left" scrollamount="6" 
               [innerHTML]="fullMarqueeText">
      </marquee>
    </div>
    
    <!-- Grid Content Section -->
    <div *ngIf="!openProjectDialog && !openGridDialog" 
         #scrollableContent 
         class="table-grid-outer table-grid-outer-scrollable" 
         id="scroll">
      
      <div class="grid-container-panel" style="height: 100%;">
        <button *ngIf="showScrollTopButton" 
                class="btn btn-secondary back-to-top" 
                (click)="scrollToTop()">
          <i class="fas fa-arrow-up"></i> Back to Top
        </button>
      </div>
      
    </div>
  </kendo-dialog>
</div>```


.table-grid-outer-scrollable {
  overflow: auto;
  max-height: calc(80vh - 100px);
  text-overflow: inherit;
}

@ViewChild('scrollableContent', { static: false }) scrollableContent: ElementRef;

ngAfterViewInit() {
  $('#scroll').parent().addClass('custom-scroll');
  this.addScrollListener();
}

public addScrollListener(): void {
  setTimeout(() => {
    if (this.scrollableContent) {
      this.scrollableContent.nativeElement.addEventListener('scroll', this.onScroll.bind(this));
    }
  }, 100);
}

public onScroll(): void {
  const scrollTop = this.scrollableContent.nativeElement.scrollTop;
  this.showScrollTopButton = scrollTop > 300;
}

public scrollToTop(): void {
  this.scrollableContent.nativeElement.scrollTo({ top: 0, behavior: 'smooth' });
}

ngOnDestroy(): void {
  if (this.scrollableContent) {
    this.scrollableContent.nativeElement.removeEventListener('scroll', this.onScroll.bind(this));
  }
}

How to Execute a Javascript Callback based on a Variable or Parameter

I have an array that is passed to React from a Laravel back end, representing columns in a database. I iterate over this array to construct headings for a table.

For each column, I want to run a callback function to mutate or transform the corresponding data (of each row) for each column.

For example, a Boolean would be transformed, so “Yes”, or “No” for 1 or 0 (a TinyInt). Here is what I have so far.

const callbacks = {
    name: function(name) {
        console.log(name);
    },
    completed: function(name) {
        console.log(name);
    },
    created_at: function(name) {
        console.log(name);
    },
    updated_at: function(name) {
        console.log(name);
    },
};

The React component that builds each row of the table is below.

export default function Row({ can, buttons, row }) {
    
    

    return (
        <>
            {
                Object.keys(row).map((k, i) => {
                    if(k !== "id") { 
                        return ( <td key={ i } className="whitespace-nowrap p-4">{ row[k] }</td> )
                    }
                })
            }
            { buttons(can, row.id) }
        </>
    );
}

Where the { row[k] } is outputted, is where I need to transform the data, based on the available callback functions and the column name, found in the variable k.

Can anyone help me figure this out? There’s likely an easy way to do this dynamically but I don’t know enough Javascript to figure it out.

I tried using an array to “map” the column names to the callback function, but I couldn’t get that to work.

I also may need to associate a column name to a different callback function, such as a callback function named active for numerous column names, ie completed, banned, has_uploaded, etc – anything that could also be Boolean.

Cannot find module when running Node.js app with PM2 and TypeScript path aliases

I’m encountering an issue when trying to run my ExpressApp application using PM2. The project is written in TypeScript, and I’m using path aliases defined in my tsconfig.json file. The build completes successfully, but when I start the app with PM2, I get the following error:

 Error: Cannot find module '@/config/routes'
 Require stack:
 - /Users/nicolasbispo/projetosgabriel/athenasbackend/build/index.js
     at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
     at Function.Module._resolveFilename (/Users/nicolasbispo/projetosgabriel/athenasbackend/node_modules/tsconfig-paths/src/register.ts:115:36)
     at Module.Hook._require.Module.require (/Users/nicolasbispo/.nvm/versions/node/v20.11.1/lib/node_modules/pm2/node_modules/require-in-the-middle/index.js:81:25)
     at require (node:internal/modules/helpers:176:18)
     at Object.<anonymous> (/Users/nicolasbispo/projetosgabriel/athenasbackend/src/index.ts:8:1)
     at Module._compile (node:internal/modules/cjs/loader:1376:14)
     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
     at Module.load (node:internal/modules/cjs/loader:1207:32)
     at Function.Module._load (node:internal/modules/cjs/loader:1023:12)
     at Object.<anonymous> (/Users/nicolasbispo/.nvm/versions/node/v20.11.1/lib/node_modules/pm2/lib/ProcessContainerFork.js:33:23) {
   code: 'MODULE_NOT_FOUND',
   requireStack: [
     '/Users/nicolasbispo/projetosgabriel/athenasbackend/build/index.js'
   ]
 }

my tsconfig.json

{
    "compilerOptions": {
        "lib": ["ES2016", "ES2017", "DOM"], //DOM Necessary due to puppeteer package i use in the app
        "target": "ES2017", 
        "module": "commonjs",
        "moduleResolution": "node",
        "outDir": "./build",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "sourceMap": true,
        "esModuleInterop": true,
        "useDefineForClassFields": true,
        "strictNullChecks": true,
        "rootDirs": ["./src"],
        "baseUrl": "./",
        "paths": {
            "@/*": ["./src/*"],
        },
    },
    "include": ["./src/**/*.ts", "./src/**/*.js", ],
    "exclude": ["build", "./node_modules/*"]
}

My src/index.ts file

import "reflect-metadata";

import express, {
    type Express
} from "express";
import "dotenv/config";
import routes from "@/config/routes";
import { SERVER_PORT } from "./config/constants";
import cors from "./middlewares/cors";
import errorMiddleware from "./middlewares/error.middleware";

const app: Express = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(errorMiddleware);
app.use(cors);
app.use(routes);


app.listen(SERVER_PORT, () => {
    console.log(`[server]: Server running at: http://localhost:${SERVER_PORT}`);
});

package.json scripts

"build": "npx tsc --build",
"start": "pm2 start build/index.js --name backendathenas --watch --node-args="-r tsconfig-paths/register"",
"deploy": "pm2 delete backendathenas || true && npm run build && npm run start",

I did a lot of adjusts in tsconfig file, but none of those seems to fix the problem, the problem only occurs when using alias source imports.

I read some solutions to use ts-loader or tsconfig-paths-webpack-plugin but im not that sure if including webpack in my backend app would be the best solution

How to dyanamically get the data on sql using d3.js with recursive functions?

I built a tree with d3.js. The Head and children as shown in the image attached:
https://www.awesomescreenshot.com/image/51112170?key=ef216990b59101f1fa063f72df525fb4

If it is ordinary HTML and Javascript, it will show children:
https://www.awesomescreenshot.com/image/51114459?key=1c64ecfe53c7a0f818aa5dfad4a76d90

Now the goal is pull out the children like E, F, G as dynamic users from the SQL

In the first level, children is working just like on the first image.

But the next children wont show up. Example: John Smith here has 1 childnode name Hanah (as Level 2- or F 1st image) then Hanah has childnode name Abby (Level 3 or G on first image).

And here is the code:

`const downlineUsersData = @json($downlineUsers['downline']);
    
    const simplifiedDownlineData = Object.values(downlineUsersData).map(userWrapper => ({
        name: `${userWrapper.user.name} ${userWrapper.user.lastname}`,
        profilePicture: userWrapper.user.profile_picture ? "{{ asset('') }}" + userWrapper.user.profile_picture : defaultProfileImage,
        status: userWrapper.user.acountStatus,
        children: []   
    }));


    const treeData = {
        name: uplineUsername,
        profilePicture: uplineImage,
        children: simplifiedDownlineData
    };

    function addDownlineUsers(parent, downlineUsers) {
        if (!downlineUsers || downlineUsers.length === 0) return;

    parent.children = downlineUsers.map(user => {
        const childNode = {
            name: `${user.user.name} ${user.user.lastname}`,
            profilePicture: user.user.profile_picture,
            status: user.user.acountStatus,
            children: []
        };

        if (user.downline && user.downline.length > 0) {
            addDownlineUsers(childNode, user.downline);
        }
        return childNode;
    });

        downlineUsers.forEach((user, index) => {
            if (user.downline && user.downline.length > 0) {
                console.log("Recursively adding downline for", user.name, user.downline); 
                addDownlineUsers(parent.children[index], user.downline);
            }
        });
    }
`

How can I fix GLSS Shading on THREE.js so it shows an accurate day-night cycle on an earth?

I’m working on a 3D Model of the earth for a project, and I am having a problem. Originally, I was using no shading, and added both materials to a group, with THREE.AdditiveBlending. This led to what is seen in the image below, where the lights that show up on the night texture show up throughout the day too.

Original model of the earth

Next, I switched over to GLSL. I’m new to it, so I apologize if my code is terrible. I’m trying to get it so that no lights are shown if the dayTexture is there. In the image below, you can see that this just ends up with the area where the nightTexture is supposed to be a dark blue blur.
Current problem with the shading
You can ignore the atmosphere and clouds, that is something that was added after the previous screenshot.

So far, I have swapped over from blending to GLSL, with my current code being here:

<script id="earthVertexShader" type="x-shader/x-vertex">
    //varying means the value is passed in the both the vertex and fragment shader, so a vector3 is passed to the fragment shader
    varying vec3 varyNormal;
    varying vec3 varyPosition;
    void main(){
    //basically prevents the model from being distorted, when orbitControls are used
    varyNormal = normalize(normalMatrix * normal);
    //position of the vertex in the world space (where the earth is)
    varyPosition = vec3(modelViewMatrix * vec4(position, 1.0));
    //gets the final position for the rendering
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
</script>
 <!-- fragment shader deals with colors, while vertex is for points on the 3d shape-->
<script id="earthFragmentShader" type="x-shader/x-fragment">
    uniform sampler2D dayTexture;
    uniform sampler2D nightTexture;
    uniform vec3 lightDirection;
    uniform vec2 resolution;
    varying vec3 varyNormal;
    varying vec3 varyPosition;
        
    void main(){
        vec3 lightDir = normalize(lightDirection);
        float dotData = dot(varyNormal, lightDir);
        //takes info abt the light and the normal of the vertex to calculate the brightness of the vertex
    float blendFactor = smoothstep(-0.1, 0.1, dotData);                 
    //gets brightness of the current vertex
    vec2 uv = gl_FragCoord.xy / resolution;
    vec4 dayColor = texture2D(dayTexture, uv);
    vec4 nightColor = texture2D(nightTexture, uv);
    
    // Blend day and night textures
        vec4 finalColor = mix(nightColor, dayColor, blendFactor);
        gl_FragColor = vec4(finalColor.rgb, 1.0);
    }
</script>

In addition, here is where I add the nightTexture to the earth:

//values needed for the shading: texture and where the light is from
    const dayTexture = new THREE.TextureLoader().load(dayTimeTexture);
    const nightTexture = new THREE.TextureLoader().load(nightTimeTexture);
    const lightDirection = new THREE.Vector3(-3.5, 0.5, 1.5).normalize();
    //changed to shaderMaterial for the shading
    const nightShader = new THREE.ShaderMaterial({
        //uniforms are just the data that the shader uses we defined earlier
        uniforms: {
            dayTexture: {value: dayTexture},
            nightTexture: {value: nightTexture},
            lightDirection: {value: lightDirection},
            resolution: {value: new THREE.Vector2(window.innerWidth, window.innerHeight)},
        },
        vertexShader: document.getElementById("earthVertexShader").textContent,
        fragmentShader: document.getElementById("earthFragmentShader").textContent,
        transparent: true,
        blending: THREE.NormalBlending,
    });
    
    const lightMesh = new THREE.Mesh(geometry, nightShader)
    earthGrouping.add(lightMesh);

The daytimeTexture that is added is a meshPhongMaterial using a imgmap, I also tried that before realising that does not work for a ShaderMaterial. I think it has something to do with the blending and/or transparency in the fragment shader, but I am not the most sure.

Any help would be greatly appreciated!