How to access JSON information from fueleconomy.gov API using JavaScript?

How would I go about accessing the following api with Javascript? https://www.fueleconomy.gov/feg/ws/ They state that “Data are available in either JSON or XML format.” and I have no clue how to actually access it in JSON format.

I’m new to using APIs and my end goal is to be able to view the MPG of user searched vehicles.

I’ve used the following code to get a working XML response in the console:

console.log('starting')
request.open('GET', 'https://www.fueleconomy.gov/ws/rest/vehicle/emissions/31873', true)

request.onload = function () {
    var parser, xmlDoc;
    var data = this.response

    parser = new DOMParser();
    xmlDoc = parser.parseFromString(data,"text/xml");

    console.log(xmlDoc)
}

request.send()

Filter Algorithm preferably in python

Good day to y’all!
So… I’m trying to figure out how to “translate” a word list from java script to python.
In java script it’s written like this: word,word2,word3,…, but in Python I need a quotation mark (“) surrounding every word. The list has over 10000 words, so to do it manually is no option.
My thinking here is to “search” for the commas (,) and then put a ” in front and behind every word.
idk if this would work, the “sketch” of my code doesn’t, but if someone knows something about this, please let me know!

Thanks,
— Me

Trigger-run a Google Sheets script to fetch URL data from Yahoo Finance in batches

Prelude – this is quite a long post but mostly because of the many pictures to clarify my issue 🙂

I have been pulling company data from Yahoo! Finance, first for only a few stocks, but currently for hundred of stocks (and soon to be thousands). I am currently pulling this data live, with one urlFetch per stock ticker each time I load the spreadsheet. This presents three problems:

  • It takes a long time for the sheet to load as it is making hundreds of requests to Yahoo!
  • I regularly get rate limited on Google side (max. 20k url fetches per day)
  • I might get rate-limited on Yahoo! Finance side

I am therefore looking for a better way:

  • Instead of calling Yahoo for each ticker each time the spreadsheet loads, I will run a google script that fetches data for each ticker once per day

Consider the following simplified example sheet (tab db):

enter image description here

The current script reads:

function trigger() {
  const db = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('db');
  const tickers = db.getRange('A2:A' + db.getLastRow()).getValues().flat();

  for (var row = 0; row < tickers.length; row++) {
    var data = yahoo(tickers[row]);
    db.getRange(row + 2, 2, 1, 3).setValues(data);
  }
}

function yahoo(ticker) {
  return [ticker, "SOME", "DATA", "MORE"]
}

Please note that for purposes of testing, yahoo() is simply returning an array. In reality, the yahoo() function pulls JSON data from Yahoo! After running the script, the spreadsheet looks like:

enter image description here

So far so good. But if the list is not 3 but 5000 tickers long, running the script as-is will get me rate-limited quickly (or waiting very long for the spreadsheet to load). Therefore, I thought about the following:

  • Each time the script is run, it will only pull data for 5 tickers. The script will be run once per minute. (5 tickers and per minute for the purposes of this thread)
  • The script will keep track of the last time it downloaded data for each ticker

Assume that the list currently looks like this:

enter image description here

Assume that today is May 31st, and the script is run:

enter image description here

Starting at the top of the lists, the script should want to update 5 tickers that have not yet been updated today:

  • BLK in row 2 has already been updated today, so it is ommitted
  • AAPL was last updated yesterday, so it is the first ticker that gets queried with Yahoo!
  • etc.

Now row 2 to 9 have updated data. The second time the script is run, it should update the next five. Again starting from the top, looking for the first 5 tickers either (1) without a “last run” date or (2) a run date before today:

enter image description here

As you can see, lines 11 to 15 are now updated too. TSLA was skipped, because (for whatever reason), it already was updated today.

Here is the same list again, just with 2 more tickers. If the script is run a few times on june 1st, the result will be like this:

enter image description here

  • 3 batches of 5 tickers
  • one batch of 2 tickers

This works great if the Yahoo! Finance service would always return data for each ticker. However, it will not. For example because:

  • it has no data for a certain ticker
  • the request is timing out

I believe I need a solution to keep track of errors while downloading data. Assume the script is run again a few times (triggered by a once-per-minute trigger in Google script) on june 2nd, and have the following result:

enter image description here

We see two tickers (JPM and ORCL) where data could not be updated. Both are marked in the error column, filled by the script-to-be.

Let’s assume we run the script again on june 3rd. On this day, JPM data is downloading perfectly, but ORCL again is generating an error. Yahoo! didn’t return any data. The error column is updated to 2.

enter image description here

If a ticker did not get data returned for 2 attempts in a row (error = 2), it should be forever skipped. I will fill it in manually at some point, or look into whether I have typed in a non-existing ticker for instance.

Keeping that of errornous downloads prevents the script from getting stuck. Without it, if there are 5 tickers at the top of the list that keep throwing errors, the script will never go past beyond those 5. It will try to attempt to download data from Yahoo over and over for these tickers.

In this last picture, we see the result of the script being run on june 4th. I have colored again the batches (5 tickers) that were updated per run/ minute.

enter image description here

I tried my best to explain how I am thinking of building a error-proof downloading from Yahoo! Finance. In the rest of my spreadsheet, whenever I need metadata from company, I can simple take it from this db tab instead of querying Yahoo! over and over.

My issue is that my scripting skills are limited. I am not overseeing how to start building this. Could someone please:

  • Give me a start with (pseudo) code OR
  • Give feedback on my thoughts. Am I missing something here that could present a problem?

PS. I understand that I am still making 5 urlfetches per time the script is run. It was suggested to me that I should batch these 5 together (which would prevent me from being rate limited at least on Google’s side). This is a great idea, but I found it difficult to understand how it works, so I would rather first have a script that works and that I can follow. In a later stage, I will definitely upgrade / make it more efficient 🙂

If you’ve read all the way until here, thank you so much. Any help is greatly appreciated!

Stop infinite page reload when navigating back using ajax

I am using WordPress along with an ajax theme and I am also using an ajax search plugin.

In order to stop the page being reloaded and continue to use ajax when clicking a search result in the ajax search I have been provided with the following code:

    let dom_observer = new MutationObserver(function(mutation) {
    if ( typeof Pjax != 'undefined' ) {
        let newContent = document.querySelector(".asl_r");
        let pjax = new Pjax({
                   cacheBust: false,
                   elements: "a", // default is "a[href], form[action]"
                   selectors: ["title", "#header nav", "#aside", "#footer", "#content"] 
                });
        pjax.refresh(newContent);
        jQuery('.asl_r .item').off('click.body').one('click.body', function(){
            document.body.click();
        });
    }
});
let container = document.documentElement || document.body,
    config = { attributes: false, childList: true, subtree: true, characterData: false };
dom_observer.observe(container, config);

This works fine, but I have an issue where if you navigate to a page and then hit the back button in a browser the previous page will load but will start to infinitley reload, without this code I can navigate back fine.

I have tried removing cacheBust but this does not help, if someone with knowledge of js/ajax could provide any advice it would be much appreciated.

Thanks

Fabric js duplicate “upper-canvas”

I am using fabricjs in a react app and I am simply rendering an image on a canvas.
Here is my react component:

import {fabric} from "fabric";
import maptest from '../assets/images/maptest.jpeg';

function getDivDimensions() {
  const {innerWidth: width, innerHeight: height} = window;
  return {
    width,
    height
  };
}

function Mapblock() {
  const [height, setHeight] = useState(0);
  const [canvas, setCanvas] = useState(null);
  const initCanvas = () => (
    new fabric.Canvas('c', {
      height: calcHeight(),
      width: calcHeight()
    })
  );

  function calcHeight() {
    let divHeight = document.getElementById('mapDiv').clientHeight;
    return divHeight;
  }

  useEffect(() => {
    function handleResize() {
      setHeight(calcHeight);
    }

    setCanvas(initCanvas());
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [])

  useEffect(() => {
    console.log("canvas effect", canvas);
    if (!canvas) {
      return
    }
    canvas.on('mouse:wheel', function(opt) {
      var delta = opt.e.deltaY;
      var zoom = canvas.getZoom();
      zoom *= 0.999 ** delta;
      if (zoom > 15) zoom = 15;
      if (zoom < 0.5) zoom = 0.5;
      canvas.zoomToPoint({ x: opt.e.offsetX, y: opt.e.offsetY }, zoom);
      opt.e.preventDefault();
      opt.e.stopPropagation();
    });

    let image = new fabric.Image(document.getElementById('image'), {
      left: 0, top: 0
    });
    image.lockMovementX = true;
    image.lockMovementY = true;
    image.selectable = false;
    canvas.setDimensions({
      width: image.width, height: image.height
    })
    canvas.add(image);
    canvas.renderAll();

  }, [canvas])
  return (
    <div id="mapDiv" className="overflow-y-clip">
      <canvas id="c"></canvas>
      <img id="image" src={maptest} className="hidden"/>
    </div>
  )
}

export default Mapblock;

However the generated div for the canvas is this:

    <div id="mapDiv" className="overflow-y-clip">
      <div className="canvas-container" style="width: 626px; height: 626px; position: relative; user-select: none;">
        <div className="canvas-container" style="width: 1600px; height: 1600px; position: relative; user-select: none;">
          <canvas id="c" className="lower-canvas" width="1600" height="1600"
                  style="position: absolute; width: 1600px; height: 1600px; left: 0px; top: 0px; touch-action: none; user-select: none;"></canvas>
          <canvas className="upper-canvas " width="1600" height="1600"
                  style="position: absolute; width: 1600px; height: 1600px; left: 0px; top: 0px; touch-action: none; user-select: none; cursor: move;"></canvas>
        </div>
        // duplicate redundant upper-canvas
        <canvas className="upper-canvas " width="626" height="626"
                style="position: absolute; width: 626px; height: 626px; left: 0px; top: 0px; touch-action: none; user-select: none; cursor: default;"></canvas>
      </div>
      <img id="image" src="/static/media/maptest.64a5034fde914bdc70c2.jpeg" className="hidden canvas-img"/>
    </div>

The duplicate upper-canvas is not letting a certain area of the canvas be zoomable.
So where is this coming from and how do I fix it?

How to modify Json Data with same key

[{
    "id": 86,
    "userid": 695,
    "fieldid": 1,
    "staff_id": 220,
    "createdDate": "2022-04-25T09:19:01.000Z",
    "fname": "VISHWAS",
    "field_name": "General",
    "value": "very nice ",
    "first_name": "GANESH",
    "last_name": "JOSHI"
},
{
    "id": 87,
    "userid": 695,
    "fieldid": 2,
    "staff_id": 220,
    "createdDate": "2022-04-25T09:19:01.000Z",
    "fname": "VISHWAS",
    "field_name": "Discipline",
    "value": "excellent",
    "first_name": "GANESH",
    "last_name": "JOSHI"
},
{
    "id": 88,
    "userid": 695,
    "fieldid": 3,
    "staff_id": 220,
    "createdDate": "2022-04-25T09:19:01.000Z",
    "fname": "VISHWAS",
    "field_name": "Medical",
    "value": "A+",
    "first_name": "GANESH",
    "last_name": "JOSHI"
}]

and i want to get object like this .

 [{
    "id": 88,
    "userid": 695,
    "fieldid": 3,
    "staff_id": 220,
    "createdDate": "2022-04-25T09:19:01.000Z",
    "fname": "VISHWAS",
    "field_name": "Medical",
    "value": "A+",
    "first_name": "GANESH",
    "last_name": "JOSHI"
}]

OnlyFans Login Register

There are a number of reasons you might be struggling to log in to your OnlyFans login account. If you’re using your phone, make sure you have the latest iOS or Android operating system installed and that you’re connected to WiFi to avoid data usage charges.

Leaflet Multipolyline with dynamic rings

for the usage of multipolylines with leaflet, i have to instantiate the polyline like this…

var polyline = L.polyline([[], []], {color: generateRandomColor()}).addTo(map);

How do i instantiate the polyline with a dynamic quantity of rings(empty arrays)?

How can i do that?
Thanks!

Rng NaN js how can i solve?

I made a short ‘program’ in Javascript for random numbers. But i always get NaN.

function timer(){
    console.log("timer");
    clicked();
    setTimeout(timer, 3000);
};
function clicked(){
    var randomness = randomize();
    console.log("clicked");
    //document.title = randomness;
    console.log(randomness);
};
function randomize(){
    return Math.floor(Math.random*6);
};

Cannot remove white bar in the top website

I need help with removing the navigation bar completely from the website
when I remove it from html it just makes (!) another white bar in the bottom

It also appears when I resize the chrome tab

I want to get rid of all of this..

Canva website example: https://www.canva.com/design/DAFCSBRJ9Oc/J8MP4clHYoNIJNTN2wDFyA/view?website#4

I have already looked up google but my limited experience in code can’t help me here.

Please help

how to prevent socket.io from returning all multiple added chat messages twice? and only return the single added message once

[I am trying to make a littlechat with socket.io + node express, the problem is that when emitting the socket it returns in the browser not only the message that I have added, but all the previous ones, so that in the browser view I only have correct messages added i have to refresh the browser]

[index.js]

const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const fs = require("fs").promises;
const path = require("path");
const { customAlphabet } = require("nanoid");
const nanoid = customAlphabet("1234567890", 5);
const productosRouter = require("./routes/productosRouter");
const chatRouter = require("./routes/chatRouter");
require("dotenv").config();

app.set("view engine", "ejs");
app.set("views", "./views");
app.use(express.static(path.join(__dirname, "public")));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/api/productos", productosRouter);
app.use("/api/chat", chatRouter);

app.get("/", (req, res) => {
  fs.readFile("productos.txt", "utf-8").then((productos) => {
    res.render("form", { productos: JSON.parse(productos) });
  });
});


app.get("/:id", (req, res) => {
  fs.readFile("productos.txt", "utf-8").then((data) => {
    const type = JSON.parse(data);
    const producto = type.find((producto) => producto.id === req.params.id);
    res.render("form", {
      producto,
    });
  });
});

app.post("/", async (req, res) => {
  const productos = await fs.readFile("productos.txt", "utf-8");
  const producto = JSON.parse(productos);
  const newProducto = {
    id: nanoid(),
    price: req.body.price,
    title: req.body.title,
    thumbnail: req.body.thumbnail,
  };
  producto.push(newProducto);

  await fs.writeFile("productos.txt", JSON.stringify(producto));

  res.render("form", {
    productos: producto,
  });
});

io.on("connection", async (socket) => {
  const fs = require("fs");
  const type = await JSON.parse(fs.readFileSync("productos.txt"));
  socket.emit("new-products", type);
  socket.on("chat", async (payload) => {
    const fs = require("fs");
    const type = await JSON.parse(fs.readFileSync("chat.txt"));
    type.push(payload);
    fs.writeFile("chat.txt", JSON.stringify(type), async (err) => {
      if (err) {
        console.log(err);
      }
    });
    socket.emit("chat", payload);
  });
  socket.emit("chat", await JSON.parse(fs.readFileSync("chat.txt")));
});

const port = process.env.PORT || 8080;
server
  .listen(port, () => {
    console.log(`App listening on port ${port}!`);
  })
  .on("error", (err) => {
    console.log(err);
    throw err;
  });

[socket.js]

let socket = io();

const msg = document.querySelector("#msg");
const btnChat = document.querySelector("#chatBtn");
const chat = document.querySelector("#chat");
const email = document.querySelector("#email");
const form = document.querySelector("#form");

form.addEventListener("submit", (e) => {
  e.preventDefault();
  if (email.value === "" || msg.value === "") {
    alert("Email and message are required");
  } else {
    socket.emit("chat", {
      email: email.value,
      msg: msg.value,
      date: new Date().toLocaleString(),
    });
    msg.value = "";
  }
});

socket.on("new-products", () => {
  fetch("api/productos")
    .then((response) => {
      return response.json();
    })
    .then(function (data) {
      if (data.length < 1) {
        return (document.querySelector(
          "tbody"
        ).innerHTML = `<h1 class='text-center'>Start adding some products to view the collection...</h1>`);
      } else {
        let tbody = document.querySelector("tbody");
        let thead = document.querySelector("thead");
        let tr = document.createElement("tr");
        let th = document.createElement("th");
        th.innerHTML = "#";
        th.setAttribute("scope", "col");
        tr.appendChild(th);
        th = document.createElement("th");
        th.innerHTML = "Title";
        th.setAttribute("scope", "col");
        tr.appendChild(th);
        th = document.createElement("th");
        th.innerHTML = "Price";
        th.setAttribute("scope", "col");
        tr.appendChild(th);
        th = document.createElement("th");
        th.innerHTML = "     Preview";
        th.setAttribute("scope", "col");
        tr.classList.add("text-center");
        tr.appendChild(th);
        thead.appendChild(tr);
        data.forEach((product) => {
          let tr = document.createElement("tr");
          tr.classList.add("text-center");
          let th = document.createElement("th");
          th.setAttribute("scope", "row");
          th.innerHTML = product.id;
          let td2 = document.createElement("th");
          td2.setAttribute("scope", "row");
          let td3 = document.createElement("th");
          td3.setAttribute("scope", "row");
          let td4 = document.createElement("th");
          td4.setAttribute("scope", "row");
          let img = document.createElement("img");
          img.src = product.thumbnail;
          img.style.width = "80px";
          img.style.height = "80px";
          td2.innerText = product.title;
          td3.innerText = `$${product.price}`;
          td4.appendChild(img);
          tr.appendChild(th);
          tr.appendChild(td2);
          tr.appendChild(td3);
          tr.appendChild(td4);
          tbody.appendChild(tr);
        });
      }
    });
});

socket.on("chat", () => {
  fetch("api/chat")
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      let correo;
      let mensaje;
      let fecha;
      data.forEach((dato) => {
        correo = dato.email;
        mensaje = dato.msg;
        fecha = dato.date;
        chat.innerHTML += `<div class="card">
          <div class="card-header">
            <h5 class="card-title text-primary">${correo}</h5>
            <h6 class="card-subtitle mb-2 text-muted">${fecha}</h6>
          </div>
          <div class="card-body">
            <p class="card-text text-warning">${mensaje}</p>
          </div>
        </div>
        <br>
        `;
      });
    })
    .catch((error) => {
      console.log(error);
    });
});

[form.ejs]

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=10" />
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor"
      crossorigin="anonymous"
    />
    <title>MVC EJS products</title>
    <style>
      input::-webkit-outer-spin-button,
      input::-webkit-inner-spin-button {
        -webkit-appearance: none;
        margin: 0;
      }
      input[type="number"] {
        -moz-appearance: textfield;
      }
      .container {
        margin-top: 277px;
      }

      @media screen and (max-width: 940px) {
        .container {
          margin-top: 0;
        }
        h1 {
          font-size: 1rem;
        }
      }
    </style>
  </head>
  <body class="container-fluid">
    <h1
      style="
        font-family: arial;
        font-weight: 700;
        line-height: 60px;
        height: 60px;
        text-align: center;
      "
      class="mb-4 bg-dark text-white"
    >
      WELCOME, FEEL FREE TO ENTER YOUR PRODUCT!
    </h1>

    <form id="formx" action="/" method="POST">
      <div class="mb-3">
        <input
          type="text"
          placeholder="What is your product?"
          class="form-control shadow-none"
          id="title"
          name="title"
          required
        />
      </div>
      <div class="mb-3">
        <input
          type="number"
          placeholder="Price"
          class="form-control shadow-none"
          id="price"
          name="price"
          required
        />
      </div>
      <div class="mb-3">
        <input
          type="url"
          placeholder="Image URL"
          name="thumbnail"
          class="form-control shadow-none text-dark"
          id="thumbnail"
          required
        />
      </div>
      <div class="mb-3 form-check">
        <input type="checkbox" class="form-check-input" id="exampleCheck1" />
        <label class="form-check-label" for="exampleCheck1">Featured</label>
      </div>
      <button
        style="height: 65px; font-weight: 700"
        class="btn btn-light border w-100 fs-3"
        type="submit"
      >
        SEND TO LIST
      </button>
    </form>

    <table class="table mt-5 container">
      <thead class="table-warning"></thead>
      <tbody></tbody>
    </table>

    <%- include ('chat') %>
    <script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2"
      crossorigin="anonymous"
    ></script>
    <script src="/socket.io/socket.io.js"></script>
    <script src="./socket.js"></script>
    <script src="./restart.js"></script>
  </body>
</html>

[chat.ejs]

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body class="container">
    <div class="bg-light">
      <h3 class="text-dark ms-2 fs-4">MESSAGE CENTER</h3>
      <div class="text-center">
        <form action="/" method="POST" id="form">
          <input
            style="outline: none; border: none"
            class="form-control shadow-none text-dark bg-white mb-3 w-100"
            type="email"
            maxlength="150"
            required
            name="email"
            placeholder="Enter your email"
            id="email"
          />

          <input
            style="outline: none; border: none"
            class="form-control shadow-none text-dark bg-white mb-3 w-100"
            type="text"
            maxlength="314"
            name="msg"
            placeholder="Type you message here..."
            id="msg"
            required
          />
          <button
            style="font-weight: bold"
            type="submit"
            class="btn w-25 btn-success"
            name="chatBtn"
            id="chatBtn"
          >
            SEND
          </button>
        </form>
        <br />
      </div>
      <div>
        <ul class="text-dark" id="chat" style="font-weight: bold"></ul>
      </div>
    </div>
    <script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2"
      crossorigin="anonymous"
    ></script>
    <script src="/socket.io/socket.io.js"></script>
  </body>
</html>

[chat.txt and productos.txt]

[]

Merging data:application/octet-stream;base64 video chunks into a file

I have an upload button on my page which user can click to upload a video. If video is large, Javascript’s File Reader can’t handle it. So I’ve implemented a function that slices uploaded video into chunks with ‘data:application/octet-stream;base64,’ label at the beginning. Meanwhile the function sends each chunk to the NodeJS backend, where I use some ‘fs’ approaches to merge the video file back and save it as an mp4 file on my disc. The problem is that the file is ’empty’. It’s recognized by my PC as an mp4 file, there is no error of wrong file format. But the video has no content and it’s 0 seconds long. How can I merge chunks properly to make the mp4 file work?

Frontend:

let reader;
let file;
const slice_size = 1024;

const start_chunks_upload = (e) => {
    event.preventDefault();

    reader = new FileReader();
    file = e.target.files[0];
    
    upload_file_chunks(0);
}

const upload_file_chunks = (start) => {
    const next_slice = start + slice_size + 1;
    const blob = file.slice(start, next_slice);

    reader.onloadend = (e) => {

        if (e.target.readyState !== FileReader.DONE) {
            return;
        }

        $.ajax({
            type: 'POST',
            url: 'http://localhost:5000/video',
            data: {
                video: next_slice < file.size ? e.target.result.replace('data:application/octet-stream;base64,', '') : null,
                is_done: next_slice < file.size ? null : true,
            },
            success: function(data) {
                const size_done = start + slice_size;
                const percent_done = Math.floor((size_done / file.size) * 100);

                console.log(percent_done + '%');

                if (next_slice < file.size) {
                    upload_file_chunks(next_slice);
                } else {
                    console.log('done');
                }
            }
        });
    };

    reader.readAsDataURL(blob);
}

video_upload_button.addEventListener('change', (e) => start_chunks_upload(e));

Backend:

let string = '';

app.post('/video', (req, res) => {

    if (req.body.is_done) {

        let buff = new Buffer.from(string, 'base64');

        fs.writeFileSync('/one.mp4', buff);
        
        fs.writeFile("/two.mp4", string, 'base64', function(err) {
            console.log(err);
        });

        fs.appendFile('/log.txt', string, function (err) {
            if (err) {
                console.log(err);
            } 
        })
    } else {
    
        if (req.body.video !== undefined) {
            string += req.body.video;
        }
        
        return res.json({ok: 1,});
    }

})

shows ‘ERR_INVALID_ARG_TYPE’

var http=require(‘http’)
var fs=require(‘fs’)

http.createServer(function (req,res) {

fs.readFile("sampleServer.html",function(err,data){
    res.writeHead(200,{'Content-Type':'text/html'})
    res.write(data)
    res.end()
})

}).listen(7000)