upload image to node js server + javascript and display in the same page with ajax jquery

I need to upload a image(jpg||png||jpeg) to the server I created with node js.

I have the router and the requestHandlers.. that redirect to this function:

  function reqUpload(request, response) {
    var form = new formidable.IncomingForm();
    form.parse(request, function (error, fields, files) {
        lastFileUploaded=files.up.originalFilename;
        if (files.up.originalFilename.match(/.(jpg|jpeg|png)$/i)) {
            //check if alredy exists
            fs.access(files.up.originalFilename, fs.F_OK, (err) => {
                if (err) {
                    fs.rename(files.up.filepath, files.up.originalFilename, function (err) {
                        if (err) {
                            fs.unlink(files.up.originalFilename);
                            fs.rename(files.up.filepath, files.up.originalFilename);
                        }

                        var data;
                        fs.readFile('./html/std.html', 'utf8', function (err, data) {
                            if (err) {
                                console.error(err);
                                return
                            }
                            response.writeHead(200, { "Content-Type": "text/html" });
                            response.write(data);
                            response.end();
                            
                        });
                    })
                }else{
                    console.log("Already exists, replacing it!");
                    fs.rename(files.up.filepath, files.up.originalFilename, function (err) {
                        if (err) {
                            fs.unlink(files.up.originalFilename);
                            fs.rename(files.up.filepath, files.up.originalFilename);
                        }
                })}

            });
        } else {
            console.log("format not accepted! try again.");

        }

This is working if I upload my file via a button and the form action =”/reqUpload”
however, I need to load in the same page.

How do I do it with ajax + jquery?

I need to display the image uploaded in the same page I uploaded it, without refreshing the page.

How to create Google calendar link date in Javascript 2022?

In 2022 the create Google calendar event link looks like this:

https://calendar.google.com/calendar/u/0/r/eventedit?sf=true&output=xml&text=sometext&location=somelocation&details=somedetails&dates=20220418T013000Z/20220416T020000Z

How do you formate such date in Javascript?

const formatDate = (date) => {
 ???
};
const myDate = new Date();
const myFormattedDate = formatDate(myDate);
console.log(myFormattedDate)

expecting output:

20220418T013000Z

Any nice looking and easy solution (rather than getHours(),getMinutes(),etc.)?

Return multiple “roles” from JSON Array

I am trying to return multiple “roles” to a DataTable. Every single role has a specific “title” and “class”, which then is returned to the datatable column.

var $role_number = full['roles'];
var $roles = {
    1: { title: 'WorkShop Leader', class: 'badge-light-primary' },
    2: { title: 'Planner', class: 'badge-light-secondary' },
    3: { title: 'Operator', class: 'badge-light-warning' },
};

These are the roles available. And then I return this:

return (
    '<span class="badge rounded-pill ' + $roles[$role_number].class + '">' + 
    $roles[$role_number].title + '</span>'
);

This works if the JSON Object has only one role (for example, role 1: WorkShop Leader).
But I want “roles” to be an array, because one user can have more than one role.

So this user has only one role:

{
    "id": 1,
    "first_name": "Albert",
    "second_name": "Cognoms",
    "roles": [1],
    "status": 1
}

And it works properly:
enter image description here

But this user has two roles, and it doesn’t show both badges:

{
    "id": 1,
    "first_name": "Albert",
    "second_name": "Cognoms",
    "roles": [1, 2],
    "status": 1
}

enter image description here

If someone knows a better way to display role badges using an array, I would really appreciate the help. I know the solution must be something easy, but I can’t get my mind clear on this.

Thanks in advance!

Hello everyone, I am learning javascript mongoDB and have a question to ask

async function a(){
    await note.save().then(()=>{
        console.log('Phonebook:')
    })
    await Person.find({}).then(people=>{
        people.forEach(person=>{
            console.log(person.name,person.number)
        })
        
    })
    mongoose.connection.close()
}
a()

The above code snippet executes without problems.But if I put mongoose.connection.close() behind the forEachfunction

async function a(){  
    await note.save().then(()=>{
        console.log('Phonebook:')
    })
    await Person.find({}).then(people=>{
        people.forEach(person=>{
            console.log(person.name,person.number)
        })
        mongoose.connection.close()
        
    })
    
}
a()

the process doesn’t end. Why?

Repeating variable length segments in Regex

I’m trying to match the following with this Regexp:

/(?<route>(?:.*/){1,2}?)(?<group>(?:.*/){1,2}+)?/
  • route/group/
  • route1/route2/group/group2/
  • route/group1/group2/
  • route/

Tried to make the first group lazy and the second one greedy and optional but it doesn’t match. What am I missing?

Formatted date as String converted to date wrong

I am trying to store date in DB using the current timezone.
I have used library date-fns-tz When I convert the date as a string is okay, but when I want to create that string as a Date it is still a problem.

    const date = new Date();
const date_string = formatInTimeZone(
  date,
  "Europe/Rome",
  "yyyy-MM-dd HH:mm:ss"
);

console.log(date_string); //2022-04-16 11:46:28  (Right time)
const current_date = new Date(date_string); // 2022-04-16T09:46:28.000Z   (Converted to 2h back)

npm run build get stuck and not working properly

I am trying to use npm run build on my project but when it is getting build it stucks at packaging favicon.[hash].png… and quits building .also it does not create the dist folder I intend to create. this is my package.json

 {
  "name": "forkify",
  "version": "1.0.0",
  "description": "recipe application",
  "default": "index.html",
  "scripts": {
    "start": "parcel index.html",
    "build": "parcel build index.html --dist-dir ./dist"
  },
  "author": "sponge bob",
  "license": "ISC",
  "devDependencies": {
    "@parcel/transformer-sass": "^2.4.1"
  },
  "dependencies": {
    "core-js": "^3.22.0",
    "fractional": "^1.0.0",
    "regenerator-runtime": "^0.13.9",
    "parcel": "^2.4.1",
    "sass": "^1.50.0"
  }
}

any idea on what should I do?

Create valid JSON from the id’s of LI’s in an unordered list

I’m trying to create valid JSON from the id’s of li’s in a nested unordered list: e.g here is an example list

<ul class="list">
            <li id="p1">1234</li>
            <li id="p2">1234
                <ul>
                    <li id="s1">sdfg</li>
                    <li id="s2">sdfg
                        <ul>
                            <li id="sq1">sdfg</li>
                            <li id="sq2">sdfg</li>
                        </ul>
                    </li>
                </ul>   
            </li>
            <li id="p6">1234</li>
            <li id="p8">1234</li>
</ul>

The JSON should read something like this:

[
    {
        "item": "p1"
    },
    {
        "item": "p2",
        "data": [
            {
                "item": "s1"
            },
            {
                "item": "s2",
                "data": [
                    {
                        "item": "sq1"
                    },
                    {
                        "item": "sq2"
                    }
                ]
            }
        ]
    },
    {
        "item": "p6"
    },
    {
        "item": "p8"
    }
]

I’m trying to create it like this:

let $arr = []
document.querySelectorAll("ul.list li").forEach($li=>{  
if( $li.querySelector("ul:first-of-type") ){
let $data = [];
$li.querySelectorAll("ul:first-of-type li").forEach($li1=>{
data.push(  {"item":$li1.id })
})
$arr.push( { "item":$li.id,"data":$data } )
} else {
$arr.push( { "item":$li.id } )
}           
})

But it’s not creating the correct JSON – any clues / help that creates the correct JSON much appreciated thanks in advance

IOS app crashes on first load in production build – React Native Expo

I am in a very confusing situation where my expo built app runs perfectly fine in my local environment but after building with EAS and when I run it on TestFlight the app crashes on the first load. But surprisingly when I open again it works fine.

Errors based on App store connect crash report

enter image description here

Error recorded on my crash logging service sentry
enter image description here

With current debugging I am only able to find that EXUpdatesAppController is an expo-updates module but not sure why its throwing an exception.

Would be great if someone can help me out with this as I am not to experienced with Expo and React native

the code under else which is inside a loop does not execute when the if statement is false

searchBtn.addEventListener('click', () => {
  const para = document.createElement('p');
  section.appendChild(para);
  for(i=0; i < database.length; i++) {
    if(searchInp.value === database[i].en || searchInp.value === database[i].tr) {
      para.textContent = `${database[i].en} = ${database[i].tr}`;
    } else {
      para.textContent = 'Not found!';
    }

  } 

  searchInp.value = '';
})

In the code above I can’t get the string ‘Not found!’ printed out when the value I enter into the input field doesn’t match with the one in database. What am I missing here? That is not the first time I am having this issue with the else part.

Base64 Decode – Javascript – PHP

I have the next string with base 64 encoded:

aJjueq22q2O202ZzZdpjPO6Cr32p0cc22jeaceupcjd2Z2SuPg2J6rwupOQzS62e3cC2eWS2gC2P232a2p925w==

When I decoded with base64_encode function in PHP I received the next string:

$key = base64_decode($key);
.3K��yd-}ڟv7qr7vgd>

But in JS I did the next:

const keyDecoded = Buffer.from(key, "base64").toString("ascii");

And I received a different decoded string:

h↑nz-6+cj<.$d3K-▲]@6yd6-☼[}→Z▼vgvgd.>

How is it possible? I need to get a string like the first (PHP)

Animated gradient library (JS) that doesn’t reset after changing page

I was searching a simple JS library that could provide me an animated gradient. I found some such as Gradientify. The only problem is that if I change or reload the page, the effect reset to the original color, as it was intended. I was wondering, then, if there was a way (changing library, writing a new little script, …) to have a seamless transition, so that the color goes on from where it was on the previous page.

I hope my answer is clear. Thanks in advance to everyone.

javascript Math and css percentage

I have a progress div container and an xhr request posting base64 images to the server.

The progress indicator div looks as follows:

<style>
.progresscover {
 background: #eee;
 width:100%;
 height: 3px;
 position: relative;
 text-align: left;
 }
 .progress{
 width:0%;
 height:100%;
 background: purple;
 position:absolute:
 left:0px;
 top:0px;
 bottom:0px;
  }
</style>
<div class="progresscover"><div class="progress"></div></div>

from the XHR request i get following values
loaded: 102533, total: 703227
The loaded obviously changes till its equal to the total..

what is the math to increase the width of the “progress” bar incrementally in percentages?

Why items appends to the redux rather than replace?

I’m newbie to Reactjs. The problem I’m encountered:

When Article page loads in the first time, all is fine and there are 10 articles shown. When I click on the browser back button, and then I go to the Article page for the second time, the article-list will be duplicated (so, it will be 20 articles). If I do so again, it will be 30 articles and so on ..

I want to know, why the result of API call appends for the Redux and not replace? In other word, how can I clean the Redux on page load every time? The expected result is seeing always 10 item (articles) on the page Article when I open it.


Here is a simplified of the element (for navigating to the list of articles) in the main page:

import Pages from "Constants/Pages";

const Component = () => {

    const history = useHistory();
    const navigateWithToken = (page) => {
        history.push(page);
      }
    };
    
    return (
        <div className="d-flex align-items-center flex-column py-1 ">
          <div
            className="main-footer-btn-article"
            onClick={() => navigateWithToken(Pages.Articles)}
          ></div>
          <span className="main-footer-btn-text">Articles</span>
        </div>
    )
};

export const ArticlesBtn = memo(Component);

Also, here is the Article page:

import { memo, useEffect } from "react";
import { useHistory } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";

import PostItems from "SharedComponents/PostItems";
import { getAllPosts } from "Redux/Actions";
import Pages from "Constants/Pages";

const Page = () => {
  const posts = useSelector((state) => state?.articles?.posts?.items);
  const dispatch = useDispatch();
  const { push } = useHistory();
  useEffect(() => {
    dispatch(getAllPosts());
  }, []);

  const onClickPost = (item) => {
    push({
      pathname: Pages.SingleArticle,
      state: {
        postId: item.id,
        title: item.subject,
        is_saved: item.is_saved,
      },
    });
  };

  return (
    <div className="full-height overflow-auto">
      { 
        posts?.map((item, index) => {
          return (
            <PostItems
              {...item}
              key={item.id}
              index={index}
              onClickPost={() => onClickPost(item)}
            />
          );
        })
      }
    </div>
  );
};

export default memo(Page);

Also here is the API call:

const getAllPosts = (page = 1) => {
  return async (dispatch: ReduxDispatch) => {
    //"posts?for=for_website"
    dispatch(toggleLoading(true));
    try {
      const { data } = await axios({
        method: "GET",
        url: "posts?for=for_mobile",
        params: { page: page },
      });
      const items = data?.data?.data;
      const pagination = {
        current_page: data.data.current_page,
        last_page: data.data.last_page,
      };
      dispatch(
        dispatchItemToRedux({
          type: ReducerTypes.GET_ALL_POSTS,
          payload: {
            items,
            pagination,
          },
        })
      );
    } catch (err) {
      return Promise.reject(err);
    } finally {
      dispatch(toggleLoading(false));
    }
  };
};