skip to Main Content

For study reasons I need to use some of these network APIs like fetch or axios but to get a LOCAL file, so WITHOUT using fs module, or WITHOUT importing them.

I tried with both fetch and axios, but they have not implemented this "feature" to get a local file, also because I think it’s not so secure/safe.

fetch:

return new Promise((resolve, reject) => {
    fetch('file://users.js')
    .then(data => {
        console.log(data);
        resolve(data);
    })
    .catch(error => {
        console.error('Errore durante il recupero del file:', error);
        reject(error);
    });
});

I get this error:

cause: Error: not implemented… yet…

axios:

return new Promise((resolve, reject) => {
        axios.get('file://users.js')
        .then(response => {
            console.log(response.data);
            resolve(response.data);
        })
        .catch(error => {
            console.error('Errore durante il recupero del file:', error);
            reject(error);
        });
    });

I get this error:

generatedMessage: false,
code: ‘ERR_ASSERTION’,
actual: ‘file:’,
expected: ‘http:’,
operator: ‘==’

Is there some other network api that let me to that?

2

Answers


  1. To fetch() files on file: protocol in the browser you can create a browser extension, in "host_permissions" set file:///*, then you can fetch file: protocol using absolute path.

    You can also fetch() file: protocol using deno.

    Other options include WICG File System Access API showOpenFilePicker() or showOpenDirectoryPicker() where implemented, and <input type="file"> which is implemented in all modern browsers.

    Login or Signup to reply.
  2. You can create an endpoint in your app to send the file by using res.sendFile function.

    app.post('/', (req, res, next) => {
    const File_Path = req.body.filepath;
    res.sendFile(File_Path,{root: __dirname});
    });
    

    Now you can call this endpoint providing any path by axios and fetch and it will give you the file data.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search