N
N
Nadim Zakirov2021-07-15 08:10:55
JavaScript
Nadim Zakirov, 2021-07-15 08:10:55

Why is the FileSystem API needed at all?

No matter how much I think, but in fact it is a useless thing! After all, it does not give real access to the disk, only to a certain virtual area. However, after all, with the same success, you can write your own implementation of a virtual file system, though, again, it is not clear why this can be useful at all.

Has anyone used the FileSystem API in real projects? Interested in your experience.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
TheOnlyFastCoder2, 2021-07-16
@TheOnlyFastCoder2

You can use new FileReader() instead of the FileSystem API; it allows you to download and read the file without
any difficulty. But if you want to overwrite the file or create a new one, then you can't do without using the server side along with the fs library for Nodejs
<input id="loaderFile" type="file" >

loaderFile.addEventListener('change', ({target}) => {
  let file = target.files[0];
  const loader = new FileReader();
  if((/(.json)$/).test(file.name)) {
    loader.readAsText(file)
    loader.onload = () => {
      const res = JSON.parse(loader.result);  
      console.log(res)
   }
 }
})

here is an example of the server side
const express = require("express");
const cors = require("cors");
const app = express();


const fs = require("fs-extra");


app.use(cors())
app.use(express.json({limit: '4MB'}))

app.all("/", function(req,res) {
    if(req.body.name != undefined){   
        res.send("It's okay")   
        const name = req.body.name.replace(/(\.)/gi,"");
        
        if(!fs.existsSync(`./files/${name}`)) {
            fs.mkdir(`./files/${name}`, function(el){
                fs.writeFileSync(`./files/${name}/${name}.srt.json`, JSON.stringify(req.body.DOM) ) 
            });
        } 
        else {
            fs.writeFileSync(`./files/${name}/${name}.srt.json`, JSON.stringify(req.body.DOM) ) 
        }
    }
})

app.listen(8080)

You can access the server using the axios library
const url = "http://localhost:8080/";
const loadedFile = JSON.stringify(loadSubtittles);
const savedSub = JSON.stringify(saveSubtittles);


const data = {
  name: target.dataset.file,
  DOM: {
    "loadFile": loadedFile, 
    "saveSubtittles": savedSub
  } 
}

axios.post(url,data,{
  headers:{ 
    "Content-Type":"application/json",
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers" : "Origin, X-Requested-With, Content-Type, Accept"
  },
})
  .then ( res => res)
  .catch( err => err)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question