Get files and folders with Static HTML/JavaScript

Is there any way I can use static HTML (and/or JavaScript) in the browser to get all the files and folders of the current project?
For example, I have the following structure:

./project
├── files-and-folders
│   ├── 1.png
│   ├── 2.png
│   ├── 3.png
│   └── inner-folder
│       ├── 4.png
│       └── 5.png
├── index.html
└── index.js

I would like to open index.html in a browser, i.e. file:///path/to/project/index.html and get the list of all files and folders under the files-and-folders folder.

I know you can use fs with NodeJS and read files and folders, but I was wondering if this can be achieved using static HTML or JavaScript.

The ideea is, that I would like to get all the files and folders from the files-and-folders folder, and display them inside my index.html file as a list.

Thank you.

Error [ERR_REQUIRE_ESM]: require() of ES Module not supported : file-url

I’m getting this strange error:

Error [ERR_REQUIRE_ESM]: require() of ES Module /home/raphy/Raphy-Template/node_modules/file-url/index.js from /home/raphy/Raphy-Template/dist/src/main/main.js not supported.
Instead change the require of index.js in /home/raphy/Raphy-Template/dist/src/main/main.js to a dynamic import() which is available in all CommonJS modules

And I do not understand why this happens:

node: v16.15.0 ,
typescript": "^4.5.4 ,
O.S: Ubuntu 20.04 Desktop

This is tsconfig.json :

{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types"],
    "target": "es2021",
    "module": "commonjs",
    "lib": ["es2021"],
    "outDir": "dist",
    //"jsx": "react",
    "jsx": "react-jsx",
    "baseUrl": "./src",
    "paths": {
      "@sections/*": ["app/sections/*"],
      "@app/*": ["app/*"]
    },
    "strict": true,
    "sourceMap": true,
    "skipLibCheck": true,
    "noImplicitAny": false,
    "noImplicitThis": false,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "allowJs": true
  },
  "include": ["src/**/*"],
  "exclude": [
    "src/index.js",
    "dist",
  ]
}

And in main.ts I import file-url in this way:

import fileUrl from 'file-url'

Where I’m already importing many other packages in the same way without any problems:
For example: import validUrl from 'valid-url';
does not give any error

But in the compiled file /dist/src/main.js : I see :

const file_url_1 = __importDefault(require("file-url"));

How to solve the problem?

Passing variables betwen functions in JQuery

How can i pass var selekcija to another function? I need to pass var selekcija to another file (load-epizode.php), but my var is i another function.

var selekcija
$(document).ready(function() {
    
   $('#sezona').change(function() {
       selekcija = 1;
       selekcija = $('#sezona').val();
       console.log(selekcija);
    });
    $('#epizds').load("/filmovi2/config/load-epizode.php", {
       NewSelekcija: selekcija
    });
        
});

HTML/JavaScript quoting bug in all major browsers?

Assume, you want to shown an alert with the string content of <!-- Comment --> <script type="text/javascript"></script> in JavaScript on a HTML page. You can do that with the following code:

<!DOCTYPE html>
<html>
<head>
<title>Quoting</title>
</head>
<body>
<script type="text/javascript">
   alert('<!-- Comment --> <script type="text/javascript"></scriptu003E');
</script>
</body>
</html>

Note here the quoted > character in the </script> part of the text. This uses a JavaScript Unicode escape to prevent the HTML parser from interpreting this part of the string literal as the end of the script tag. The code above works perfectly in FF, Chrome, IE.

Now try to apply the > quoting also to the end of the comment within the string literal. This should change nothing, because the XML comment syntax should not be interpreted within script tags in HTML (and obviously is not interpreted, because the comment syntax was shown in the alert):

<!DOCTYPE html>
<html>
<head>
<title>Quoting</title>
</head>
<body>
<script type="text/javascript">
   alert('<!-- Comment --u003E <script type="text/javascript"></scriptu003E');
</script>
</body>
</html>

Interestingly, this code breaks – the alert is not printed when the page loads. The problem can be reproduced at least in FF, Chrome and IE. Am I missing something in the specs, or is that a “browser-independent” bug in the HTML parser of all major browsers?

The DOM inspector shows the following:

enter image description here

It looks like the rest of the document is interpreted as part of the script in this case.

Any ideas?

This is a Website using react which logins perfectly and works as expected on desktop [local] but gives error on mobile screen [local]

App.js

import axios from "axios";
import BlogForm from "./components/BlogForm";
import UpdateUserForm from "./components/UpdateUserForm";
import Register from "./components/Register";
import Blog from "./components/Blog";
import ResetPassword from "./components/ResetPassword";
import Profile from "./components/Profile";
import Feed from "./components/Feed";
import Dashboard from "./components/Dashboard";
import Homepage from "./components/Homepage";
import Login from "./components/Login";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import "./App.css";
import { useState, useEffect } from "react";
import NoResult from "./components/NoResult";
import ProtectedRoute from "./components/ProtectedRoute";
import auth from "./auth";
import { checkAuth } from "./helpers/helpers";
import PublicRoute from "./components/PublicRoute";

axios.defaults.headers.common["Authorization"] = localStorage.getItem("token");
axios.defaults.baseURL = "http://localhost:5000";
export default function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(
    auth.isAuthenticated()
  );

  useEffect(() => {
    if (checkAuth) {
      auth.login(() => {
        setIsAuthenticated(true);
      });
    }
  }, []);

  return (
    <Router>
      <Switch>
        <Route exact path='/'>
          {isAuthenticated ? <Homepage /> : <Login />}
        </Route>
        <PublicRoute exact path='/login' component={Login} />
        <PublicRoute exact path='/register' component={Register} />
        <PublicRoute exact path='/reset-password' component={ResetPassword} />
        <ProtectedRoute exact path='/home' component={Homepage} />
        <ProtectedRoute
          exact
          path='/create-blog'
          component={() => <BlogForm type='Create' />}
        />
        <ProtectedRoute
          exact
          path='/update-blog/:blogid'
          component={() => <BlogForm type='Update' />}
        />
        <ProtectedRoute exact path='/dashboard' component={Dashboard} />
        <ProtectedRoute
          exact
          path='/my-feed'
          component={() => <Feed type='feed' />}
        />
        <ProtectedRoute exact path='/blog/:blogid' component={Blog} />
        <ProtectedRoute exact path='/user/:userid' component={Profile} />
        <ProtectedRoute
          exact
          path='/search/:query'
          component={() => <Feed type='search' />}
        />
        <ProtectedRoute
          exact
          path='/update-user/:userid'
          component={UpdateUserForm}
        />
        <ProtectedRoute exact path='/no-results' component={NoResult} />
        <Route path='*' component={() => "404 NOT FOUND"} />
      </Switch>
    </Router>
  );
}

Login.js

import { useState } from "react";
import eyeIcon from "../images/eye.png";
import { Link, useHistory } from "react-router-dom";
import axios from "axios";
import auth from "../auth";
import { checkAuth } from "../helpers/helpers";

export default function Login() {
  const history = useHistory();
  document.title = "Login";

  const [showPassword, setShowPassword] = useState(false);
  const [loginDetails, setLoginDetails] = useState({
    email: "",
    password: "",
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setLoginDetails((prev) => {
      return {
        ...prev,
        [name]: value,
      };
    });
  };

  const handleLogin = (e) => {
    e.preventDefault();
    login();
  };

  const login = async () => {
    try {
      const res = await axios.post("/auth/login", loginDetails);
      localStorage.setItem("token", res.data);
      if (checkAuth()) {
        auth.login(() => {
          history.push("/home");
        });
      }
    } catch (err) {
      const errors = err.response.data.errors;
      console.log(errors);
      errors.forEach((err) => {
        alert(err.msg);
      });
    }
  };

  return (
    <div className='login-register-container'>
      <div className='l-container d-flex justify-center align-center'>
        <h1>
          Login to <br />
          Your <br />
          Account <span>.</span>
        </h1>
        <form className='d-flex flex-col' onSubmit={handleLogin}>
          <input
            type='email'
            name='email'
            placeholder='Enter Your Email'
            value={loginDetails.email}
            onChange={handleChange}
          />
          <label htmlFor='password'>
            <img
              className='toggle-password'
              src={eyeIcon}
              onClick={() => setShowPassword(!showPassword)}
              alt=''
            />
            <input
              type={showPassword ? "text" : "password"}
              name='password'
              placeholder='Enter Your Password'
              value={loginDetails.password}
              onChange={handleChange}
            />
          </label>
          <Link to='/reset-password'>Forgot Password</Link>
          <Link to='/register'>Not a User?</Link>
          <input type='submit' value='Login' />
        </form>
      </div>
    </div>
  );
}

This code works as expected on the desktop where I am building it on localhost but gives this error while running it on mobile browser [localhost].

It gives an err : Uncaught(in promise) TypeError : Cannot read properties of undefined (reading ‘data’).

In desktop, if there is an error while logging in it produces an alert or else user is redirected to homepage.

In the backend to the post request of http://localhost:5000/auth/login returns a token if logged in perfectly or else returns errors array.

auth.js (Backend using Node.js/Express)

router.post(
  "/login",
  [
    check("email", "Enter a Valid Email Id").isEmail(),
    check("password", "Password is required").not().isEmpty(),
  ],
  async (req, res) => {
    // Errors array
    const errors = validationResult(req);
    // If the errors array is not empty set status 400:Bad request and give the error messages in json
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    // Get the details of the user
    const { email, password } = req.body;

    try {
      let user = await db.query("SELECT * FROM USERS WHERE email=$1", [email]);
      if (user.rows.length === 0) {
        return res
          .status(400)
          .json({ errors: [{ msg: "Invalid Credentials" }] });
      }

      let found;
      let newPassword = md5(password);

      if (user.rows[0].password === newPassword) {
        found = true;
      } else {
        found = false;
      }

      if (!found) {
        return res
          .status(400)
          .json({ errors: [{ msg: "Invalid Credentials" }] });
      }

      const payload = { userid: user.rows[0].userid };

      const accessToken = jwt.sign(payload, process.env.JWT_TOKEN, {
        expiresIn: "2h",
      });

      res.status(201).json(accessToken);
    } catch (err) {
      console.log(err.message);
      res.status(500).send("Server Error");
    }
  }
);

Not getting back any data using axios and tv maze api

I’m trying to get search data using the axios plugin from the TV Maze Api

    <form method="POST" action="/results">
  <input type="text" name="searchTerm" placeholder="Search for shows">

  <input type="submit" value="Search">

</form>

I’m using a handlebar to post the information to my app.js

//Sets up results page
app.get("/results", mware.requireLogin, function(req, res) {

  const simplifiedUser = {
    username: req.user._doc.username, 
    isAdmin: req.user._doc.isAdmin
  };

  res.render("results", {
    message: req.flash('info'),
    user: simplifiedUser
  });
});

// Process the form submission
app.post('/results', async function(req, res) {

    const results = await showService.searchShows(req.body.searchTerm);
    if(results && results.shows) {
        res.render('results', {
            results: results.shows,
            searchTerm: req.body.searchTerm
        });
    } else {
        res.render('error');
    }

}); 

It then sends it off to retrieve that data but nothing is coming back. It keeps on skipping the data and goes straight ro rendering out the error message.

const showService = {

searchShows: async (term) => {
  //searches for shows
  //   /search/shows?q=query
  
    try {

      const options = {
      params: {
        term,
      }
  };

      const response = await axios.get(show_api + '/search/shows?q=', options);


    if(response && response.data){
      return response.data;
    } else {
      return ["did not work"];
    }
      //console.log(response);
    } catch (error) {
      console.error(error.response.data);
    }
  }

};

Any solution would help a lot thank you

Highcarts: Hide xAxis categorie when serie is not visible

I have stacked column chart where I defined a serie per xAxis categorie. When I click the serie in the legend, the serie becomes hidden, which is what I want. But if the serie is not on the edge of the XAxis, the categorie remains visible. I would like to remove the xAxis label for the series that are not visible without removing them from the legend, so they can reappear when they are clicked again in the legend. Any ideas on how I can accomplish this?

chart

I am using HighchartsReact from 'highcharts-react-official'. The code to set my options is the following:

    const getHighChartsSeries = (columns: string[], tsvdata: tsvdata[]) => {
        const series = [];
        for (let serie in columns) {
            const seriedata: tsvdata = tsvdata.filter((m) => m.sample_id === columns[serie])[0];
            const seriesColors = getSeriesColors(seriedata.data.map((m) => Number(m.seq_freq)));
            const data = seriedata.data.map((sd, index) => {
                return {
                    x: Number(serie),
                    y: Math.round(Number(sd.seq_freq) * 10000) / 100,
                    name: sd.clone_id,
                    color: seriesColors[index],
                };
            });
            const serieEntry: Highcharts.SeriesOptionsType = {
                name: columns[serie],
                type: 'column',
                data: data,
                color: baseColor,
            };
            series.push(serieEntry);
        }
        return series;
    };

    const setHighChartsOptions= (tsvdata: tsvdata[]) => {
        const columns = tsvdata.map((item) => item.sample_id);
        const series = getHighChartsSeries(columns, tsvdata);
        const options: Highcharts.Options = {
            chart: {
                type: 'column',
                zoomType: 'xy',
            },
            title: {
                text: props.title,
            },
            xAxis: {
                showEmpty: false,
                categories: columns,
            },
            yAxis: {
                min: 0,
                max: 100,
                title: {
                    text: 'Percentage',
                },
            },
            tooltip: {
                headerFormat: '<b>{point.x}:</b><br/>',
                pointFormat: '<b>{point.name}:</b> {point.y} %<br/>',
            },
            plotOptions: {
                column: {
                    stacking: 'normal',
                    dataLabels: {
                        enabled: true,
                        format: '{point.name}',
                    },
                },
            },
            series: series,
            credits: {
                enabled: false,
            },
        };
        setOptions(options);
    };

WDIO:How to log each Test step as Pass/Fail in Spec report console output

I would like to log, each action/Test Step inside ‘it block (TestCase) as Pass/Fail.
I have tried to find a lot on how to achieve that but couldn’t succeed. Kindly Help me if anyone knows how to do that.

My Spec File looks like this:

const LoginPage = require('../pageobjects/login.page');
const SecurePage = require('../pageobjects/secure.page');

describe('My Login application', () => {
    it('should login with valid credentials', async () => {
        await LoginPage.open();

        await LoginPage.login('tomsmith', 'SuperSecretPassword!');
        await expect(SecurePage.flashAlert).toBeExisting();
        await expect(SecurePage.flashAlert).toHaveTextContaining(
            'You logged into a secure area!');
    });
});

And Current Console Output is:
ConsoleOutput

As we can see Describe & IT block is being logged, but I would like to see Actions as well.

like LoginPage.open,login & expect.

Is there any way we can do it?

How do I format with comma a number(value of input) in jQuery?

I want to format with comma a number what a value of input.
But, This code is not working.
jquery version is 3.6.0.

$(function(){
  $('.bid_btns_add button').on('click',function(){
    var current_value = parseInt($('#bid_price').attr('value'));
    var add_value = parseInt($(this).val());
    var total_value = current_value + add_value;

    var output_value = total_value.replace(/(d)(?=(ddd)+(?!d))/g, "$1,"); //error               
    var output_value = total_value.toLocaleString(); //error

    $('#bid_price').attr('value', output_value);
  });
  $('.bid_btn_clear').on('click',function(){
    $('#bid_price').attr('value',0);
  });
});
<button type="button" class="" value="1000">1000</button>
<button type="button" class="" value="5000">5000</button>
<button type="button" class="" value="10000">10000</button>

<input id="bid_price" type="number" class="input_price" value="0"></input> 
<button type="button" class="bid_btn_clear">x</button>

React -how to change a to input

I have a table that each row that has some td that here these 2 td are important for me and I want to change them: name & family.
I want to change each name or family td when the user clicks on it.
how can I handle this event?

this is my table td :

finalList.map((i, index) => {
  return (
    <tr className="contactItem" id={i.id} key={i.id}>
      <td>{String(index + 1).padStart(2, "0")}).</td>
      <td id="editName" onClick={(e) => inlineEditHandler(e, i.name)}>{i.name}</td>
      <td id="editFamily" onClick={(e) => inlineEditHandler(e, i.family)}>{i.family}</td>
      <td>
        {String(i.numbers[0]).substring(7, 11) +
          "***" +
          String(i.numbers[0]).substring(0, 4)}
      </td>
      <td className="itemBTNS">
        <button
          className="deleteBTN"
          onClick={() => contactDeleteHandler(i.id)}
        >
          X
        </button>
        <button
          className="editBTN"
          onClick={() => contactEditHandler(i)}
        >
          Edit
        </button>
      </td>
    </tr>
  );
})

I want to set this event for the second and third td.
And note that I don’t want to use the contentEditable attribute.

  inlineEditHandler = (e, i) => {
    this.setState({
      [e.target.id]: i,
    });
  };

editName and editFamily are my states.
What should I do in the inlineEditHandler function or other stuff to change the tagName from td to input or something like this?

How to remove specific field from table in node js mongodb?

comment: 'hi'
replies: array
likes: array

i have to remove comment field and every time i delete it deletes the whole collections.
This is the code

deleteComment: async (root, { commentID, comment}) => {
try{
const deleteComment = await CommentModel.findOne(
 {_id:commentID}
);
if(deleteComment){
  const remove = await CommentModel.deleteOne(comment)
  return(remove)
}


}catch(err){
  console.log(err)
}

},

greenlock-express Action questions

After setting greenlock-express, we checked that https is applied
After that, I ran it on Nodemon, and when I accessed the site again, Nodemon continued to run again and again So I thought that config.json in the greenlock.d folder seems to be constantly being updated

After creating the nodemon.json file, I made it ignore the greenlock.d folder
Is it correct that the config.json was updated continuously and nodemon repeatedly restarted?

Maximum call stack size exceeded while adding object to empty array of references in mongodb

I have these two schemas

const postSchema = new Schema(
  {
    creator: { type: Schema.Types.ObjectId, ref: "User" }
  }
);

module.exports = mongoose.model("Post", postSchema);
const userSchema = new Schema({
  name: { type: String, required: true },
  posts: [ { type: mongoose.Types.ObjectId, ref: "Post" } ]
});

module.exports = mongoose.model("User", userSchema);

and I have this code

mongoose
  .connect(MONGODB_URI)
  .then(async (result) => {
    const user = await User.findById(userId);
    console.log(1, user) // 1

    const post = new Post({ creator: user })
    console.log(2, post) // 2

    await post.save()
    console.log(3, post) // 3

    user.posts.push(post)
    console.log(4, user) // 4

    await user.save()
    console.log(5, user) // 5
  })
  .catch((err) => console.log(err));

I placed these console logs so you can see where is the problem.
If there are zero posts in the database collection and user.posts is an empty array, if we try to console.log value of the user or the post after we push a post to the user.posts we would get an error saying “Maximum call stack size exceeded”. So, logs 1, 2, and 3 would all work and console.log 4 would result in an error. If we remove these console.logs everything would work fine. Can anyone explain such strange behavior?

Note: This happens only if there are zero posts in the database and user.posts array is empty.