Electron Intercept file:/// protocol to read inside zip files - javascript

I would like to read inside zip archives with Electron as if they were folders, like so /myfolder/myarchive.zip/picture.jpg. To do this I'm thinking about intercepting the file protocol
protocol.interceptFileProtocol('file', (request, callback) => {
if (insideZipArchive) {
//respond with zip file contents
} else {
//defaultBehavior
}
}, (error) => {
if (error) console.error('Failed to register protocol')
})
How do I invoke the default behavior? Also doing an AJAX request inside the interceptor and serving files like this callback({data: new Buffer(xhr.responseText)})does not seem to work.

It looks like this could be solved with a service worker, as shown here:
How to intercept all http requests including form submits

Related

Meteor reports my server method does not exist

fairly new to Meteor and JS, doing a lot of reading and research. I have been following an example of an HTTP request but I keep getting an error "404, method Abc not found":
This is how my JS file looks like:
if (Meteor.isServer) {
Meteor.methods({
Abc: function () {
this.unblock();
return Meteor.http.call("GET", //HTTP REQUEST TEXT);
}
});
}
if (Meteor.isClient) {
Meteor.call("Abc", function(error, results) {
console.log(error);
console.log(results);
});
}
Why the server method is not found if it is in the same file? I only want to show the content of the HTTP response.
Debugging and re-reading the tutorials.
Apparently, your code is loaded only on the client side. You should separate the client and the server logic by using the "client" and "server" folders respectively . Or in your example you should use "both" folder.

ReactJS ServiceWorker storing the same code in multiple cache files

I am trying to add a serviceworker to an existing React app with this filesystem layout:
Filesystem
Basically a bit of initialization code is stored in the public folder, and all code of importance is in the src folder. In the serviceWorker.js file, I made an array of filenames to cache and call that array in the 'install' event listener, and if I check DevTools I can see that the filenames are present in the cache: when I preview the data in Chrome DevTools however, I see that the code inside the cached files is all from index.html. In fact, I can add anything I want to the filename array and I will find it in cached storage only to find that it is storing the index.html code. It seems like no matter what file I try to add to the cache, only index.html gets loaded.
ServiceWorker.js:
let CACHE_NAME = "MG-cache-v2";
const urlsToCache = [
'/',
'/index.html',
'/src/App.js',
'/monkey'
];
self.addEventListener('install', function (event) {
//perform install steps
event.waitUntil(
caches.open(CACHE_NAME).then(function (cache) {
console.log('Opened MG_Cache');
return cache.addAll(urlsToCache);
}).catch(function (error) {
console.error("Error loading cache files: ", error);
})
);
self.skipWaiting();
});
self.addEventListener('fetch', function (event) {
event.respondWith(caches.match(event.request).then(function (response) {
if (response) {
return response;
}
return fetch(event.request);
})
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(async function () {
const cacheNames = await caches.keys();
await Promise.all(
cacheNames.filter((cacheName) => {
//Return true if you want to remove this cache,
//but remember that caches are shared across the whole origin
return;
}).map(cacheName => caches.delete(cacheName))
);
})
})
Portion of index.html:
<script>
if ('serviceWorker' in navigator)
{
window.addEventListener('load', function () {
navigator.serviceWorker.register('serviceWorker.js').then(function (registration) {
// Registration was successful
console.log("ServiceWorker registration successful with scope: ", registration.scope);
}, function (err) {
// registration failed :
(console.log('ServiceWorker registration failed: ', err));
});
});
}
</script>
Google Devtools Preview:
All files are the same
I have tried a variety of naming strategies in the filename array but all have ended with the same result. At this point I'm at a complete loss.
EDIT: While this does not solve my problem, I found an answer to another problem that gives a little guidance. It seems like the server never finds the file I request and thus returns index.html. I tried placing the serviceWorker.js file in the src folder and moving the service worker registration to App.js and got an error:
`DOMException: Failed to register a ServiceWorker for scope ('http://localhost:3000/src/') with script ('http://localhost:3000/src/serviceWorker.js'): The script has an unsupported MIME type ('text/html'). `
This suggests that the server somehow doesn't have access to the src folder, only public. Any idea why that may be?
An important piece of information I left out it that I'm using Create-React-App. Because of the enforced layout of the filesystem, the serviceWorker must be placed in the public folder: at the same time, the scope of service workers by default is the folder that they are placed in. According to this answer, changing the scope of the service worker to be a level above the folder that it is in requires adding to the HTTP header response of the service worker (not entirely sure what that means), and doing something like that assumes you have some form of a local server set up. Alas, thus far I have just been using npm start to test my app and pushing onto nsmp to make the site live, thus have negleted to do any form of server implementation myself (I know, not very smart of me).
My hotfix was to create a new temporary app with the npx create-react-app my-app --template cra-template-pwa command, copy all files pertaining to service workers from that app (serviceWorkerRegistration.js, service-worker.js, index.js, potentially setupTests.js), and paste them into my app. Then I could simply follow this tutorial. Now my site works offline.

Node.js/Azure: upload HTML to BlobStorage

I have a frontend which sends the HTML of that page to a Node.js server. The server should then send that HTML to Azure BlobStorage.
Here is my express route to handle this:
router.post("/sendcode", function(req, res) {
let code = "";
code = req.body.code;
console.log(code);
let service = storage.createBlobService(process.env.AccountName, process.env.AccountKey);
service.createContainerIfNotExists("htmlcontainer", function(error, result, response) {
if (error) {
throw error;
} else {
service.createBlockBlobFromStream("htmlcontainer", code, function(err, result, response) {
if (err) {
throw err;
} else {
console.log(result);
console.log(response);
}
});
}
});
});
When I call this route, I receive this in my console:
<html><style>* { box-sizing: border-box; } body {margin: 0;}</style><body></body></html>
How can I send it to BlobStorage? Avoid the method I used as it maybe wrong because I can't figure out what function to use because of scarce documentation.
There are many answers on stack overflow, you can follow this one and adjust it to your needs:
Uploading a file in Azure File Storage using node.js
So after trying a little bit, i was able to send it not from stream but after writing it to a file, sending that file through createBlockBlobFromLocalFile function in azure-storage module and deleting the file from disk.
I know this isnt the most efficient method out there but it got my work done.
The problem i was facing was that after uploading html code in a block blob(without file operation), its content type was application/octet which i wanted to be text/html. So i had to perform one more operation to change its content type, which i found to be a little difficult due to unavailability of documentation and examples in javascript.

Node js serve file body from server and download in browser

I have a file repository and when i call it from the browser it automatically downloads the file and this is fine.
But i want to do this request on my server, and then serve the file result to the browser. Here is the example of the get request from my server.
downloadFile(req , res , next) {
let options = {
url: 'url to my file repo',
};
request(options, function (err, resp, body) {
if (err) {
res.status(500).send("");
return
}
for (const header in resp.headers) {
if (resp.headers.hasOwnProperty(header)) {
res.setHeader(header, resp.headers[header]);
}
}
resp.pipe(res);
})
}
The request is working fine, and when i access my server from the browser it starts downloading the file. Everything seems to work fine except one thing, the file can't be opened. This file format can't be opened, says me the image player (if the file is image for example).
Where is the problem, Is it the way i serve the file from the server?
Thank you in advance. I lost a lot of time and can't find the solution.
Because what you probably want to send is the body of the request (e.g. the data of your image).
So instead of resp.pipe(res):
res.send(body)
Use the developer mode of your browser to check the network messages passing between the server and your browser.

JavaScript Prompt download in browser

Im simply trying to download a file from the server and prompt the download in the browser for the user to see.
What i have right now:
Client
export function downloadTemplateAction(questionnaire) {
return dispatch => {
dispatch(downloadTemplateRequestAction(questionnaire));
return request
.get(downloadGETUrl)
.end((err, res) => {
if (err) {
console.log("Download ERROR", err)
dispatch(downloadTemplateFailureAction(err, questionnaire));
} else {
console.log("Download Success", res.body)
dispatch(downloadTemplateSuccessAction(res.body, questionnaire));
}
});
}
}
Server:
export function downloadTemplateDocument(req, res){
res.download('template/Example.docx');
res.end();
}
Im facing two problems:
First: When trying to download the file via the function of the Client, the response body is null but success and nothing more happens.
Second: When contacting the get API via the browser localhost:3002/api/download, the download works but the received file is empty. There should be text in it.
What am i doing wrong here?
Browser can't prompt a download progress because your request is sent via XMLHttpRequest.
Physical access to the file is needed for the browser to be aware of any download.
You could use download attribute to tell browser to download linked ressource.
original answer

Categories

Resources