Zip image stream using archiver and send as express response

This is on Node/Express/Typescript. I’m trying get an image on my file system, stream it to a zip file, and then stream this zip file to the client. I have to make sure every step is streamed since this will expand to zipping up multiple files, which need to be streamed to the client as a zip.

I have the following code:

import express, { Application, Request, Response } from "express";
import fs from "fs";
import stream from "stream";
import archiver from "archiver";

app.get("/images", async (req: Request, res: Response) => {
    const r = fs.createReadStream("appicon.png");
    const ps = new stream.PassThrough();

    // stream the image
    stream.pipeline(
        r,
        ps,
        (err) => {
            if (err) {
                console.log(err);
                return res.sendStatus(400);
            }
        }
    );


    // zip the image and send it
    let archive = archiver("zip");

    output.on("end", () => {
        console.log(archive.pointer() + " total bytes");
        console.log("archiver finalized");
    })

    archive.on('error', (err) => {
        return res.status(500).send({
            message: err
        });
    })

    res.attachment('output.zip');
    ps.pipe(archive); 
    archive.pipe(res);



    archive.finalize();

});

However, when I access my /images route, I get an output.zip file which is empty.

I feel like I’m messing up the order of my pipes somehow.

What am I missing?

Why there is not my parameter so “children” in the function?

export const Web3ContextProvider: React.FC<{ children: ReactElement }> = ({ children }) => {
    const dispatch = useDispatch();

    const [connected, setConnected] = useState(false);
    const [chainID, setChainID] = useState(DEFAULD_NETWORK);
    const [providerChainID, setProviderChainID] = useState(DEFAULD_NETWORK);
    const [address, setAddress] = useState("");

    const [uri, setUri] = useState(getMainnetURI());
    const [provider, setProvider] = useState<JsonRpcProvider>(new StaticJsonRpcProvider(uri));

    const [web3Modal] = useState<Web3Modal>(
        new Web3Modal({
            cacheProvider: true,
            providerOptions: {
                walletconnect: {
                    package: WalletConnectProvider,
                    options: {
                        rpc: {
                            [Networks.AVAX]: getMainnetURI(),
                        },
                    },
                },
            },
        }),
    );

    const hasCachedProvider = (): boolean => {
        if (!web3Modal) return false;
        if (!web3Modal.cachedProvider) return false;
        return true;
    };

    const _initListeners = useCallback(
        (rawProvider: JsonRpcProvider) => {
            if (!rawProvider.on) {
                return;
            }

            rawProvider.on("accountsChanged", () => setTimeout(() => window.location.reload(), 1));

            rawProvider.on("chainChanged", async (chain: number) => {
                changeNetwork(chain);
            });

            rawProvider.on("network", (_newNetwork, oldNetwork) => {
                if (!oldNetwork) return;
                window.location.reload();
            });
        },
        [provider],
    );

    const changeNetwork = async (otherChainID: number) => {
        const network = Number(otherChainID);

        setProviderChainID(network);
    };

    const connect = useCallback(async () => {
        const rawProvider = await web3Modal.connect();

        _initListeners(rawProvider);

        const connectedProvider = new Web3Provider(rawProvider, "any");

        const chainId = await connectedProvider.getNetwork().then(network => Number(network.chainId));
        const connectedAddress = await connectedProvider.getSigner().getAddress();

        setAddress(connectedAddress);

        setProviderChainID(chainId);

        if (chainId === Networks.AVAX) {
            setProvider(connectedProvider);
        }

        setConnected(true);

        return connectedProvider;
    }, [provider, web3Modal, connected]);

    const checkWrongNetwork = async (): Promise<boolean> => {
        if (providerChainID !== DEFAULD_NETWORK) {
            const shouldSwitch = window.confirm(messages.switch_to_avalanche);
            if (shouldSwitch) {
                await swithNetwork();
                window.location.reload();
            }
            return true;
        }

        return false;
    };

    const disconnect = useCallback(async () => {
        web3Modal.clearCachedProvider();
        setConnected(false);

        setTimeout(() => {
            window.location.reload();
        }, 1);
    }, [provider, web3Modal, connected]);

    const onChainProvider = useMemo(
        () => ({
            connect,
            disconnect,
            hasCachedProvider,
            provider,
            connected,
            address,
            chainID,
            web3Modal,
            providerChainID,
            checkWrongNetwork,
        }),
        [connect, disconnect, hasCachedProvider, provider, connected, address, chainID, web3Modal, providerChainID],
    );
    //@ts-ignore
    return <Web3Context.Provider value={{ onChainProvider }}>{children}</Web3Context.Provider>;
};

So the dev make his code open source. and i was watching his code to understand. But i saw that he uses destructuration props but in the function why there is not the world children used? like in the example i saw when the dev uses destruction like ({name, value}) then in the function, he uses the word name and value. So why in the function there is uses of the word “children”

RUM track unused Javascript / code coverage

I am searching for a tool that tracks unused Javascript of Real Users on my website.

The problem I faced was that the Coverage Report in Dev Tools told me that there was a lot of unused JS but I didn’t know which parts of the Javascript Code I could remove without breaking the website.

The problem is extremely bad if you use a Content Management System (e.g. WordPress). Often the websites end up being very pretty but they include a lot of Javascript that is not used because you didn’t need the full functionality of the theme. To remove all the unused Javascript afterwards is extremely tedious especially if the theme was bundled with things like webpack when the code is hard to understand.

=> So I head the following idea: Is there a tool that I can use that automatically tracks which lines of JS Code my visitors run. The tool would track the data and then send me a report after a month which lines of code were unused. I would be confident to delete those lines from the code of my website because no real user ever executed them. Maybe there is a RUM tool out there that has this functionality. I am aware of Istanbul JS but I didn’t found a tool/company which offers this in a RUM fashion.

best practice to validate POST request body

My Express API exposes a POST endpoint to create a user, and i need to validate data before inserting it into database, i have two methods in mind:

Method 1: Include the model’s validation in the controller and repeat it for every model:

// controllers/users.js

exports.createUser = async function (req, res) {
    const { username, email, password } = req.body;

    /* validation logic */

    /* interact with db */

Method 2: Move the validation logic to dedicated middleware:

// middleware/validators.js

exports.validateArticle = function (req, res, next) {};

exports.validateComment = function (req, res, next) {};

exports.validateUser = function (req, res, next) {
    const { username, email, password } = req.body;

    /* validation logic */

    if (!isValid) {
        return res.statusCode(400);
    }

    next();
};
// routes/users.js

const { validateUser } = require('../middlewares/validators');

router.route('/').post(validateUser, createUser);

my concern with method 2 is that the logic for one endpoint method would be scattered among many files, but which one of these methods follow best practices ?

Web: Is it possible to toggle the soft keyboard from a phone device with the press of a button? How?

I’d like to have a very simple webpage that by pressing a button would bring the soft-input keyboard on a mobile-device to show and have the user be able to press the keys from it.

I am well aware that having a text-input like field would do the job for me but I don’t want to use that. I just want to toggle it from the button press. I don’t want to have an input field, I’d get the keystrokes from a global window listener

Clicking the button the first time should show it and clicking it the second it time should hide it.

I am also aware that I can do that programatically if I build a native Android App using Kotlin/Java and same goes for an iOS app using the Obj-C/Swift counterparts but in this case I am dealing with a website so only web technologies would apply: HTML5, CSS and vanilla JavaScript

Multiple Identical Divs to only change url image

Hi I’m new to web development and I’m trying to practice by making a small site for my mom!

So basically I have this div that I want to replicate multiple times only changing the image url & the h3 caption.

<div class="col-lg-4 mb-5 col-md-6">
     <div class="wine_v_1 text-center pb-4">
          <a class="thumbnail d-block mb-4"><img src="images/im.jpg" alt="Image" class="img-fluid"></a>
         <div>
             <h3 class="heading mb-1"><a href="#">Us</a></h3>
         </div>
     </div>
</div>

I was thinking of using JavaScript to copy the div as a string to be something like ( pseudocode )

for image.length {
    getelementbyid.print (div1 + imageArray(i) + div2 + caption(i) + endofDiv ) 
}

Would this be possible? Would it make sense to do it this way or is there a more simple way?

How to detect correct object comparing same object in another array?

Here is what I went to do.

    const original = [
                      {label: 'test1', formUid: 211},
                      {label: 'test2', formUid: 204},
                      {label: 'test3', formUid: 258},
                      {label: 'test4', formUid: 1045},
                      {label: 'test5', formUid: 1096},
                      {label: 'test5', formUid: 1096},
                       
                   ];
                   
  const modified = [
                      {label: 'test1', formUid: 211},,
                      {label: 'test4', formUid: 1045},
                      {label: 'test6', formUid: 1025},
                      {label: 'test5', formUid: 1096},
  ]

I have two arrays, one is original array otherone is modified array from the original array. So what happen here is I checked original array obejct include in modified array

Considering above two deleted object I am going to modify my copy of original array, So I make copy from orginal array delete the two object that I consirder as deleted. so output is like this for now

   const CopyOforiginal = [
              {label: 'test1', formUid: 211},
              {label: 'test4', formUid: 1045},
              {label: 'test5', formUid: 1096},
              {label: 'test5', formUid: 1096},
               
           ];

this is happening in my code you can see It in snippet,

But this the problem now, you can see two same object in original array (I have set the index for example)

  original = [
                 [4]:{label: 'test5', formUid: 1096},
                 [5]:{label: 'test5', formUid: 1096},
                ]

and one object in modified array same object as above objects

modified = [ 
             [3]:{label: 'test5', formUid: 1096},
           ]

So How can I compare this ? See if we get first object from the original array and find modified array have an same object yeah there is a one it found same object from the modified array that finish

Then get second same object from the original array and check is modified array have any matching object with that , there have one but it counted before we cant get again and again same object So original array second object want to mark as deleted one

after fix all these problems final result want to be like this

const CopyOforiginal = [
                  {label: 'test1', formUid: 211},,
                  {label: 'test4', formUid: 1045},
                  {label: 'test5', formUid: 1096},

               ];

function testFunc(){
      
       const original = [
                          {label: 'test1', formUid: 211},
                          {label: 'test2', formUid: 204},
                          {label: 'test3', formUid: 258},
                          {label: 'test4', formUid: 1045},
                          {label: 'test5', formUid: 1096},

                       ];

      const modified = [
                          {label: 'test1', formUid: 211},,
                          {label: 'test4', formUid: 1045},
                          {label: 'test6', formUid: 1025},
                          {label: 'test5', formUid: 1096},
                          {label: 'test5', formUid: 1096},
      ]
      

    let originalCopy;
  let flag;
  let oForm , oIdx;
  let srcipt = [];
 
   originalCopy = [...original];
   
    original.forEach((originForm, originInx) => {
   
    let res = modified.some(item => item.formUid === originForm.formUid)
   
      if(!res){
srcipt.push(originForm.formUid + " DELETE_FROM " + (originInx+1)); //created the script for deleted form
     
        let res = originalCopy.findIndex(idx => idx.formUid === originForm.formUid); //get the index from copy of the original array
        originalCopy.splice(res, 1); //remove the object
      }
    })
   

    //document.getElementById("originalArray").innerHTML = JSON.stringify(original);
    //document.getElementById("modifiedArray").innerHTML = JSON.stringify(modified);
    document.getElementById("result").innerHTML = JSON.stringify(srcipt);
    document.getElementById("copyArray").innerHTML = JSON.stringify(originalCopy);
  }
<button onClick="testFunc()">Click</button>
originalArray : <p id="originalArray"></p>
modifiedArray : <p id="modifiedArray"></p>
result        : <p id="result"></p>
CopyOf original Array result        : <p id="copyArray"></p>

window onunload/onbeforeunload events don’t work?

I’ve used the event in other projects/games but it doesn’t seem to be working on this one. onload event is working fine tho.

Script is linked on the bottom of the html before the < /body > tag

the code in client.js

(() => {
    // Player Closes window
    window.addEventListener("beforeunload", function (e) {
        sock.emit('player-leave', player);
        alert('window.addEventListener');
    });
    window.onbeforeunload = function(event) {
        sock.emit('player-leave', player);
        alert('window.onbeforeunload');
    };
    window.onunload = function(event) {
        sock.emit('player-leave', player);
        alert('window.onunload');
    };
})();

Event doesn’t pass throu and no alert is shown.

Firestore Array of map not updating

So I’m working on a personnal project to learn react-native and firestore.

I have a a DB like this:
Db image

and I want by code to add a new battery in the array batteries.
The elements in the array are just a map{string, string}

The problem is that when I update the array with a new brand that’s work but if I want to update it with the same brand again have,
so having by the end

batteries[0]: {'brand': 'cestmoi'}
batteries[1]: {'brand': 'cestmoi'}

the db doesn’t update, don’t have any error or so.

I don’t understand why and I followed their tuto. Here is my code:

async function addData(collection, doc, value) {
    console.log(`Add data ${value.brand}`)
    try {
        const result = await firestore()
                    .collection(collection)
                    .doc(doc)
                    .set({
                        batteries: firestore.FieldValue.arrayUnion(value)
                    })
        console.log(result);
        return result;
    } catch (error) {
        return error;
    }
}

I use try catch by habit but I don’t know if the then...catch is better or not…

Thanks

Clonar texto de un text area dentro de un div con saltos de linea [closed]

necesito que cuando se presione agregar se cree un div debajo con exactamente el mismo texto que el escrito dentro del text area, con los saltos de linea incluido.

imagen de la pagina y su mal funcionamiento

 <body>
     <div id="colorInterfas">
    <p>FONDO</p>
        <input type="color" name="color" id="colorFondo">
        <input type="color" name="color" id="colorLetra">
    <p>LETRA</p>
    </div>
   
        <textarea id="input" cols="30" rows="10"></textarea>
   

    <button id="button">agregar</button>
    </div>
    <ul id="container">

    </ul>
    </body>




let text = document.querySelector('#input');
let button = document.querySelector('#button');
let container = document.querySelector('#container');
let colorPickerFondo = document.querySelector('#colorFondo');
let colorPickerLetra = document.querySelector('#colorLetra');



colorPickerFondo.addEventListener('change', () => {

text.style.background = colorPickerFondo.value

})

colorPickerLetra.addEventListener('change', () => {
text.style.color = colorPickerLetra.value

})

if (text.style.background === '') {
text.style.background = colorPickerFondo.value;

}

if (text.style.color === '') {

    text.style.color = colorPickerLetra.value;

}

button.addEventListener('click', () => {

if (text.value.trim().length !== 0) {
    let CONTENT = document.createElement('il');
    CONTENT.classList.add('content');
    CONTENT.textContent = text.value;
    CONTENT.setAttribute('style', ` background: ${text.style.background} ; color: ${text.style.color};  width: 180px; height: 180px;`);
    container.appendChild(CONTENT);

}
});

Con este codigo el texto es copiado, pero todo junto, sin los saltos de linea.

este codigo es para hacer una pagina que cree anotaciones tipo “post-it” de diferentes colores
me faltaria hacer eso y despues lograr que se acomode de la manera correcta
porque ahora mismo se quedan todos pegados xd

Muchas gracias.

Best way to restrict page access?

I’m designing a website with a form component that redirects to a “failure” or “success” component based on whether the form submits without an error or not. Here is the code I’m using:


                  await axios.post('/api/patients/', data, axiosConfig)
                  .then((response) => {
                    history.push('/success')
                  })
                  .catch((error) => {
                    history.push('/failure')
                  })

This works well even when I intentionally make a bad request by turning my network off or changing the route. However, I can type in the “/success” route in my browser and access it whether or not I’ve submitted the form. How do I restrict this behavior?

Filter timestamp from sql database and extract as a list in python

I have an sql database from node red. The table of the database contains a column with javascript date.now() timestamps e.g. 1641154320892. Another column of the table contains temperature values. I’d like to select temperature values of a specific time period.

I tried the following code:

import sqlite3
conn = sqlite3.connect('/home/ktm/Developing/test/home_automation.db')
print ("Opened database successfully")
conn.row_factory = lambda cursor, row: row[0]
c = conn.cursor()
ids = c.execute('SELECT Buero_temp FROM home_automation WHERE Zeitstempel BETWEEN '2022-01-05' AND '2022-01-07';').fetchall()
for i in ids:
    print (i)

Unfortunately, I get “SyntaxError: invalid syntax”

What am I doing wrong?

How Can I Display Images When Clicked?

I am trying to develop a card matching game. I watched a Youtube Tutorial about it. But the cards does not show up even if I write the exact code from the video. The aim is matching two same characters. The characters should show up when a portal is clicked. So what’s the problem here? Here is my JavaScript code:

document.addEventListener('DOMContentLoaded',()=>{

    const cardArray = [
        {   
            name: 'beth',
            img: 'images/beth.png'
        },  

        {   
            name: 'beth',
            img: 'images/beth.png'
        }, 

        {   
            name: 'jerry',
            img: 'images/jerry.png'
        },    

        {   
            name: 'jerry',
            img: 'images/jerry.png'
        }, 

        {   
            name: 'morty',
            img: 'images/morty.png'
        },    

        {   
            name: 'morty',
            img: 'images/morty.png'
        }, 

        {   
            name: 'mrpoopybutthole',
            img: 'images/mrpoopybutthole.png'
        }, 
    
        {   
            name: 'mrpoopybutthole',
            img: 'images/mrpoopybutthole.png'
        },  

        {   
            name: 'rick',
            img: 'images/rick.png'
        },    

        {   
            name: 'rick',
            img: 'images/rick.png'
        },

        {   
            name: 'summer',
            img: 'images/summer.png'
        }, 
        
        {   
            name: 'summer',
            img: 'images/summer.png'
        }  
    ]


cardArray.sort(()=> 0.5 - Math.random());

const grid = document.querySelector('.grid');
const resultDisplay = document.querySelector('#result');
var cardsChosen = [];
var cardChosenId = [];
var cardsWon = [];


function createBoard() {
    for(let i=0; i<cardArray.length; i++){
        var card = document.createElement('img');
        card.setAttribute('src','images/portal.png');
        card.setAttribute('data-id', i);
        card.addEventListener('click', flipCard);
        grid.appendChild(card);
    }
}

function checkForMatch(){
    var cards = document.querySelectorAll('img');
    const optionOneId = cardsChosenId[0];
    const optionTwoId = cardsChosenId[1];

    if (cardsChosen[0] === cardsChosen[1]) {
        alert('You found a match');
        cards[optionOneId].setAttribute('src', 'images/white.png');
        cards[optionTwoId].setAttribute('src', 'images/white.png');
        cardsWon.push(cardsChosen);
    }

   else {
       cards[optionOneId].setAttribute('src', 'images/portal.png');
       cards[optionTwoId].setAttribute('src', 'image/portal.png');
       alert('Sorry, try again');
   } 

   cardsChosen = [];
   cardChosenId= [];
   resultDisplay.textContent = cardsWon.length;

   if (cardsWon.length === cardArray.length/2){
        resultDisplay.textContent = 'Congratulations! You found them all!';
   }

}


function flipCard(){
    var cardId= this.getAttribute('data-id');
    cardsChosen.push(cardArray[cardId].name);
    cardsChosenId.push(cardId);
    this.setAttribute('src',cardArray[cardId].img);

    if(cardsChosen.length === 2){
        setTimeout(checkForMatch,500);
    }


}
createBoard();

});

Create a function that follows a moving text on a table

I found a function to move data between table cells but the functions never seem to stick to whatever tag is “attached” to the cell itself. I’m not sure if I was using ids wrong. I need help finding a way to “attach” a function to a tag that moves between cells.
Can you help me create a button to move a tag (unit 1) upwards and downwards through a table such that it stops at the end of the table?

Original code attached here

//Send to the "bottom"
function sendOS() {
  var node = document.getElementById("r1c1").lastChild;
  document.getElementById("r1c3").appendChild(node);
  /*
    var node = document.getElementById("r1c3").lastChild;
  document.getElementById("r1c2").appendChild(node);
  */
}

//Send to the "top"
function sendTop() {
  var node = document.getElementById("r1c2").lastChild;
  document.getElementById("r1c1").appendChild(node);
}
table,
th,
td {
  border: 1px solid black;
  width: 32px;
  height: 32px;
}
<table>
  <tr id="row1">
    <td id="r1c1">Unit1</th>
      <td id="r1c2">Unit2</th>
        <td id="r1c3">Unit3</th>
  </tr>
  <tr id="row2">
    <td id="r2c1">r1c2</td>
    <td id="r2c2">r2c2</td>
    <td id="r2c2">r2c3</td>
  </tr>
  <tr id="row3">
    <td id="r2c2">r3c1</td>
    <td id="r2c2">r3c2</td>
    <td id="r2c2">r3c3</td>
  </tr>
</table>
<!--Table ends -->
<!-------------------------------------------------------------->


<button onclick="sendOS()">move to the other side</button>
<button onclick="sendTop()">move to the right</button>