How to run shell command from javascript client-side?

I have the simplest program: 1 HTML file, 1 CSS file, and 1 JS file, just run directly on my own computer. And all I’m trying to do is that when you press a button in the program, one single shell command (Windows) is run directly on the computer. This will generate file, which in turn will be used further inside the program.

It appears you cannot access your local files through JS alone, so I installed NodeJS (which is completely new to me). But I still can’t get it to work that way either.

The only way I finally got NodeJS to host the HTML page in a way that the JS and CSS files also work, is by copying the code I got here: https://stackoverflow.com/a/13635318. (I called it server.js).

But I still haven’t been able to find a way to call upon server.js while client-sided to run that shell command. Some posts suggest using AJAX for this, like here https://stackoverflow.com/a/53897335, but I haven’t been able to find any way to successfully catch that in server.js.

How do I convert this to a functional component?

I’m trying to practice reactjs and how can I convert this class component to a functional component?

     handleChange = (e) => {
    const { name, value } = e.target;
    this.setState( {
        [name] :value
    })
  };

So far, I could only do this and I’m quite lost when it comes to the this.setState

 const handleChange = (e) => {
    const { name, value } = e.target;
  };

null is not an object (evaluating ‘user.uid’)

I want to retrieve a field value of a document in Users collection by referencing it via the where condition from Firestore. I use the context api to pass the user object of the logged in user in my app. I get this error that user.uid is null. I can’t spot where the mistake is. I have added the relevant piece of code.

EditProfile.js

const EditProfile = () => {
  const { user } = React.useContext(AuthContext);

  const [name, setName] = React.useState();

  React.useEffect(() => {
    const userid = user.uid;
    const name = getFieldValue("Users", userid);
    setName(name);
  }, []);

  
};

export default EditProfile;

passing and getting value via context

export const AuthContext = React.createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = React.useState(null);

  return (
    <AuthContext.Provider
      value={{
        user,
        setUser,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};
const AppStack = () => {
  return (
    <AuthProvider>
      <BottomTab.Navigator>
        <BottomTab.Screen
          name="ProfileStack"
          component={ProfileStack}
        />
      </BottomTab.Navigator>
    </AuthProvider>
  );
};

export default AppStack;

ProfileStack.js

export const ProfileStack = ({ navigation }) => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Profile"
        component={Profile}
      />
      <Stack.Screen
        name="EditProfile"
        component={EditProfile}
      />
    </Stack.Navigator>
  );
};

getFieldValue function

export const getFieldValue = (collection, userid) => {
    firestore()
      .collection(collection)
      .where("userid", "==", userid)
      .get()
      .then((querySnapshot) => {
        if (querySnapshot.size === 0) {
          return "";
        }
        if (querySnapshot.size === 1) {
          const { name } = querySnapshot[0].data();
          return name;
        }
      })
      .catch((e) => console.log(e));
  };

Uncaught (in promise) ReferenceError: getNFTNames is not defined

I am not so familiar with javascript, and i’m using someone else’s code, and added some new functions with parameters, and it’s throwing the following error

It’s somehow not recognizing the functions with parameters.

Uncaught (in promise) ReferenceError: getNFTNames is not defined
window.App = {
 start: function() {
  var self = this;

  Voting.setProvider(web3.currentProvider);
  NFTContract.setProvider(web3.currentProvider);
  self.populateNFTs();
 },

populateNFTs: function() {
  var self = this;
  NFTContract.deployed().then(function(contractInstance) {
    contractInstance.allNFTs.call().then(function(NFTArray) {
      for(let i=0; i < NFTArray.length; i++) {
        NFTs[NFTArray[i]] = "tokenID-" + i;
      }
      console.log("NFT Array = " + JSON.stringify(NFTs));
      self.setupNFTRows();
    })
  })
 },

 setupNFTRows: function() {
  Object.keys(NFTs).forEach(function (NFTid) { 
    $("#NFT-rows").append(
      `<tr id='NFT_ID_${NFTid}'>
          <td>NFT_ID_${NFTid}</td>
          <td>${this.getNFTNames(NFTid)}</td>
          <td>${this.getCreators(NFTid)}</td>
         </tr>`);
  });
},

getNFTNames:function (nftid){
  NFTContract.deployed().then(function(contractInstance) {
    contractInstance.getNFTname.call(nftid).then(function(v) {
      return v.toString();
    });
  });
}

}

Installing Node.js Using JavaScript Code? [closed]

I’ve been programming for decades but am new to JavaScript.

I recently began working on a new project which I want to be able to run
on Linux, Windows and Apple. After some research I decided to use HTML
and JavaScript. I was thinking/hoping I would be able to do the entire
project using only client-side coding, but it doesn’t appear like that’s
going to be the case.

I’ve encountered a point where I need to copy/move files from one location
to another.

What are my options? Node.js?

If Node.js is my only or best option, is it possible to download and
install Node.js using client-side JavaScript code? (Many of the people
who will be using the system will be computer-challenged and/or elderly.
It may be daunting for them if they need to install Node.js themselves.)

I appreciate any help.

How to write a JS function that is used by .html files in different folders?

I’m trying to call a function on my XAMPP server that dynamically changes the current stylesheet of an HTML document. This is what I’m currently doing:

document.getElementById("color-scheme").href = "../colors.css";

The colors.css is obviously one folder above the page that is using this code, hence the “../”. Now my problem is that there are dozens of pages in different folder levels that all need to access this colors.css to set the color-scheme. For example:

  • index.php (same folder)
  • news/index.php (one folder in)
  • news/january/index.php (two folders in)
    … and so on.

This means that every page that isn’t exactly one folder above colors.css doesn’t work as it can’t find the file at “../colors.css”, as the server seems to go back beyond the root to find the file.

I feel like manually adding “../” according to the folder’s level would be very bad coding, so I don’t want to do this:

function LoadColorScheme(var level) {
   var path = "";
   for (var i = 0; i < level; i++) 
      path += "../";
   path += "colors.css";
 }

Is there a better way to do this?

How to iterate through an object with key and get the value

So I am not sure why I having such a difficult time with this, but I have an object I am trying to map over to get a value from it.

For example:

let obj = {
      "lyzjmpkvbtocygakcoxu": {
        "label": "Show Time",
        "hour": "12",
        "minute": "00",
        "period": "p.m.",
        "add_time": "enabled",
        "bdlmynfythqgyzrhruhw_add_date": "December 01, 2021",
        "bdlmynfythqgyzrhruhw_stock": ""
      },
      "eueuuzvkteliefbnwlii": {
        "label": "Show Time",
        "hour": "05",
        "minute": "00",
        "period": "p.m.",
        "add_time": "enabled",
        "brtmypzvuooqhvqugjbj_add_date": "December 02, 2021",
        "brtmypzvuooqhvqugjbj_stock": ""
      }
    }

I want to be able to get this:

December 01, 2021, December 02, 2021

I was able to do this to get the values and key for “add_time”, however what I want is values for key containing the “…_add_date”.

Object.keys(obj).reduce(
          (acc, elem) => {
            acc[elem] = obj[elem].add_time;
            return acc;
          },
          {},
        );

How to get data from another page html using the same script.js?

I’m really struggling with this, I’m using fetch to get data from rest api countries, and displaying some countries in index.html. My case is that when I click on a country, I want to move to detail.html and display more data from the country I clicked on. I don’t know how to deal with this. I tried to use the same script.js in detail.html and hoped to get the e.target from the addEventListener, but the code collided as a result. It would be much easier if I created a modal in index.html, but instead of doing that I want to move to a different page and get my skills increased a bit. Should I use a backend in this case?

If you’d like to see the preview site or the codes here are the links site, code

React Redux Image Wont load

So this could honestly be as simple as just over looking it and staring for so long and being new to react but on my section component I’m loading in my backgroundImg prop wont load the image and I cant figure it out. My pictures are in the public folder and my code is in the src components folder

Also, I can get images to load in the file just not when I’m calling them through prop

Home.js This is where I am calling my component and trying to load the file in through the prop type

import React from 'react'
import styled from 'styled-components'
import Section from './Section'


function Home() {
    return (
        <Container>
            <Section 
                title="Model S"
                description="Order Online for Touchless Delivery"
                backgroundImg='/public/pictures/model-s.jpg'
                leftBtnText="Custom Order"
                rightBtnText="Existing Inventory"
            />
            <Section 
                title="Model E"
                description="Order Online for Touchless Delivery"
                backgroundImg=".Picturesmodel-e.jpg"
                leftBtnText="Custom Order"
                rightBtnText="Existing Inventory"
            />
            <Section />
            <Section />
            
        </Container>
    )
}

export default Home

//Home and styled help you stlye the component without using css

const Container = styled.div`
    height: 100vh;
`


Section.js The component for the Screen

import React from 'react'
import styled from 'styled-components'


//props are just parameters you can set when calling the component

function Section(props) {
    
    return (
        <Wrap bgImg={props.backgroundImg}>
            <ItemText>
                <h1>{props.title}</h1>
                <p>{props.description}</p>
            </ItemText>
            <Buttons>
                <ButtonGroup>
                    <LeftButton>
                        {props.leftBtnText}
                    </LeftButton>
                    <RightButton>
                        {props.rightBtnText}
                    </RightButton>
                </ButtonGroup>
                <DownArrow src='/Pictures/down-arrow.svg' />
            </Buttons>
        </Wrap>
    )
}

export default Section

const Wrap = styled.div`
    width: 100vw;
    height: 100vh;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
`

const ItemText = styled.div`
    padding-top: 15vh;
    text-align: center;
`

const ButtonGroup = styled.div`
    display: flex;
    margin-bottom: 30px;
    @media (max-width: 786px){
        flex-direction: column;
    }
`

const LeftButton = styled.div`
    background-color: rgba(23, 26, 32, 0.8);
    height: 40px;
    width: 256px;
    color: white;
    display: flex; 
    justify-content: center;
    align-items: center;
    border-radius: 100px;
    opacity: 0.85;
    text-transform: uppercase;
    font-size: 12px;
    cursor: pointer;
    margin: 8px;
`

const RightButton = styled(LeftButton)`
    background: white;
    opacity: 0.65;
    color: black;
`

const DownArrow = styled.img`
    margin-top: 20px;
    height: 40px;
    overflow-x: hidden;
    animation: animateDown infinite 1.5s;
`

const Buttons = styled.div`

`


Thanks for the help.


javascript sum of json objects

After trying to find many ways to do it here, I’m stuck with this.

I have a Json object and would like to sum all the results.
This code is showing all amounts, but not showing their sum in the end.

var str = e.data.substring(e.data.indexOf("["));
    if (IsJsonString(str)) {
        var body = JSON.parse(str);
        var data = body[1];

        if(data && data.id == "ID" && data.some.string == "string"){

            var fields= [
                data.some
              ];
              var sum = fields.reduce(function(acc, val){
                return (+acc.amount) + (+val.amount);
              }, {amount: 0});
              console.log(sum);
        }
    }

moment js need help hiding the booked time

I am working on creating an appointment application using momentjs and I don’t want to show the time that is already booked. I was able to do using a while loop but I have to pass by the index number for each time. Is there a shortcut way to do this if the bookedTime is more than 2? This is what I have so far. Any help will be appreciated:

const get24HoursTimeWithInterval = (
  interval = 30,
  startHour = 0,
  endHour = 24,
  bookedTime = [],
  timeToPrepareForNextWork = 0,
) => {
  const startTime = moment(startHour, 'h:mm A');
  const endTime = moment(endHour, 'h:mm A');
  const bookedBeginTime = moment(bookedTime[0], 'h:mm A');
  const bookedEndTime = moment(bookedTime[1], 'h:mm A');

  if (endTime.isBefore(startTime)) {
    endTime.add(1, 'day');
  }
  const timeStops = [];
  if (bookedTime.length > 0) {
    while (startTime < bookedBeginTime) {
      timeStops.push(new moment(startTime).format('h:mm A'));
      startTime.add(interval + timeToPrepareForNextWork, 'minutes');
    }
    while (bookedEndTime < endTime) {
      timeStops.push(new moment(bookedEndTime).format('h:mm A'));
      bookedEndTime.add(interval + timeToPrepareForNextWork, 'minutes');
    }
  } else {
    while (startTime <= endTime) {
      timeStops.push(new moment(startTime).format('h:mm A'));
      startTime.add(interval + timeToPrepareForNextWork, 'minutes');
    }
  }
  const slots = timeStops;

  return slots;
};
console.log(get24HoursTimeWithInterval(30, 0, 24,['12: 00 PM', '1:00 PM', '1:30 PM', '2:30 PM'], 10))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

How to compare values while looping over multiple arrays simultaneously in javscript? [closed]

First off, I know this question has been asked before but it dosent seem to match my case.

I was a doing a coding assement and had a question like this:
enter image description here

I need to loop over two arrays simultaneously and compare their values to a number. I could not figure out how to do this.

  1. Is it possible to do this with for loops?

  2. Why was my code not hitting the 3 on the outer loop?

  3. What is the optimal solution considering time and space complexity?

Arguments Object

i’m currently learning js and need to pass a test, every requirement checks out besides “should work on an arguments object”. I noticed that when I take out the Array.isArray() part of the code, it works. However then I wont pass the “return an empty array if array is not an array” part of the test.

we are allowed to ask for help on stackoverflow so I would appreciate the help. thanks 🙂

this is my code:

// Return an array with the first n elements of an array.
// If n is not provided return an array with just the first element.
_.first = function (array, n) {
  var resultArray = [];
  if (Array.isArray(arguments[0]) !== true){
    return []} 
  else if (arguments[1] > arguments[0].length){
  return arguments[0]
 } else if (typeof arguments[1] !== "number" || arguments[1] == 0 || arguments[1] < 0){
  resultArray.push.call(resultArray, arguments[0][0])
  return resultArray
 } else {
 for (var i = 0; i < arguments[1]; i++)
 resultArray.push.call(resultArray, arguments[0][i]);
 return resultArray;
}
};

html adding a comma to user inputs on a form

I have a html form taking user inputs as per below. However, when the form submits, I get the data in the back-end in the below format. Notice that the make, model, and engine capacity data has a comma and brackets yet the other fields are okey. I really do not know why this is the case. Anyone help me fix this.

Description             Details Provided
MAKE:                    ('MAZDA',)
MODEL:                   ('ATENZA',)
TRIM DETAILS:             standard
ENGINE CAPACITY (cc):     (2000,)
FUEL TYPE:                PETROL
MILEAGE (km):             120000
TRANSMISSION:             AUTOMATIC
YEAR OF MANUFACTURE:      2009