i am using electron and node js and trying to decrypt an encrypted file using crypto js, but i don't want to save it on user's local hard drive, i want to display it on video tag as i am reading it, meaning i don't want to use fs.createWriteStream after decryption, here is what i tried:
const decipher = crypto.createDecipher('des-ecb', 'a password');
const decInput = fs.createReadStream("encrypted video");
var file = decInput.pipe(decipher);
var file2 = fs.createReadStream(file);
is such thing is even possible? if i want to display the video i must have its url for source of video tag, but i can't make an URL for that file, and i cant even read it because it says object is passed to the fs.createReadStream and it says param must be string(path) or buffer or etc...
NOTE: the encryption and decryption works just fine so i ignored the rest of the code...
Similar question might already suit your needs. You already have the stream ready, let frontend reads it so that video is stored in the browser.
Related
I am working with Blazor Server in a .NET6 application, which obviously is not super JavaScript friendly. However, it appears to me that the easiest way to download a PDF is through JavaScript, so I'm using an interop to make it happen.
My PDF files are stored in a FileTable on SQL. I can pull the data quite easily into my C# code. I am also storing JPG, PNG, TXT files, etc, on the file table and these are all downloadable using the following code in my interop.
async (fileName, contentStreamReference) => {
const arrayBuffer = await contentStreamReference.arrayBuffer();
const blob = new Blob([arrayBuffer], {type: 'application/pdf'});
const url = URL.createObjectURL(blob);
const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
URL.revokeObjectURL(url);
};
Passed into my interop: The string value of the name of my PDF file, and a MemoryStream of the byte array stored in the SQL FileTable.
All file downloading works fine, regardless of the type that I set on my Blob. Downloading of the PDF seems like it works from the outside, since the download occurs without incident and the file size is identical, but opening the file results in an error. I suspect that it has something to do with header information, but I'm not entirely sure and nothing I'm finding is helping here.
The above code was found in other StackOverflow answers, and like I said, works quite nicely for everything that is not a PDF. Is there an easy solution here, or do I need to look elsewhere?
I have tried tweaking the code to do a few different things based on different answers I find, and nothing has helped make the PDF actually work, although the downloading of other files is surprisingly resilient to change.
im trying to make a js app that tells someone to log in and saves the email and password in a text file, after some googling it looks like js doesn't have access to system files so node is required.
so i searched how to do it, but i keep getting an error that says Uncaught ReferenceError: require is not defined at HTMLButtonElement
this is the JS code:
let email = document.querySelector(".txt");
let password = document.querySelector(".pass");
let log_btn = document.querySelector("button");
log_btn.addEventListener("click", () => {
let mail = email.value;
let pass = password.value;
var fs = require('fs');
let content = `email: ${mail}\n password: ${pass}`;
fs.writeFile("info.txt", content, err => {
if (err) {
console.error(err);
return;
}
console.log("file created");
});
window.location.href = "index2.html"
})
what is preventing this from working, is there something i should include or install or anything.
hope someone has the answer, thanks in advance.
NodeJS is not a thing for browsers, it's a console application (the one outputting white text in black window)
To work with HTML and NodeJS at once, you need to use a mix of NodeJS and Browser, like https://nwjs.io/ or https://www.electronjs.org/
Download NWJS, upzip it, and open the HTML file with nw.exe, then you'll get a browser where you can use require and use filesystem
If the thing you want is making a web page which connects to a server that saves the file that's another thing, see https://adevait.com/nodejs/build-a-crud-app-with-only-json-files for example
1 - If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file.
2 - If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
3 - To store some information on the client side that is considerably small, you can go for cookies.
4 - Using the HTML5 API for Local Storage.
I have an app, that allows users to upload an image, crop it and with other data save it all as html file to be used as a footer for emails. The image is given to them as base64.
Howver turns out this is not supported by Outlook, since it doesnt accept b64 data as img source.
So my idea was to save the cropped image to a file, let's say /public/avatars/avatar.png and link it's directory as a source. However I'm having trouble finding a way how to save images to to a file using JS. My allowed stack is JS and React, no node.js.
How would I do that? I can have the file as either b64 ot canvas element, so i'm flexible here, as long as it's saved to file.
I'm open to other solutions too.
You can't save a file with client language only. You have to save it to a server, own server or external server or a service like AWS.
The best solution without server-side (strangly) is to use a API for save image and get link from this API. Then you can use this link to Outlook.
You can use https://aws.amazon.com/fr/cloudfront/ free for one year with 50Go and 2 millon request monthly.
If you do not exceed 300,000 images per year you can use this service : https://cloudinary.com/pricing
You can also use https://www.deviantart.com/developers/ but that's not really the point of service.
Weird solution :
Be careful, the login and password of your FTP user will be available in the source of your code. Minimum rights must be administered.
You can use this script for talk to FTP server from JS (not tested but seems worked) : http://www.petertorpey.com/files/ae/scripts/FTPConnection.jsx
You can try something like that :
var ftp = new FtpConnection("ftp://URL") ;
ftp.login("username", "password");
ftp.cd("FOLDER") // For move to folder
ftp.put(file,"FILE.PNG") ; // File must be a File JS Object
ftp.close() ;
Lets suppose a case where a huge string is generated from a small string using some javascript logic, and then the text file is forced to be downloaded on the browser.
This is possible using an octet-stream download by putting it as an href , as mentioned in this answer :
Create a file in memory for user to download, not through server.
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.click();
}
But this solution requires 'text' to be fully generated before being pushed for the download,
hence it will have to be held in browser memory fully .
Is it possible to stream the text as it gets generated using CLIENT SIDE LOGIC ONLY ?
For example :
var inputString = "A";
var outStr = "";
for(var i = 0; i < 10000000 ; i++)
{
/* concatenate inputString to output on the go */
}
Yes & no. No because there's not a way to write to files with just client-side javascript. Kinda. You can prompt a user to download & save a file, but as you mentioned, the code must generate the whole file before that download happens. Note: By "stream" I assume you mean stream to file (constantly write to a file) & by "CLIENT SIDE LOGIC ONLY" I assume you mean in the browser.
Looks like Mozilla has been working on a way to let client-side code interact with files. Here comes the yes. Kind of. They have their own file system api that lets you interact with (write to) the local machines file system. Specifically, there's a function that lets you write an input stream to a file. However, there's a few asterisks:
1) looks like that whole system is being deprecated; they encourage developers to use OS.file over File I/O
2) You have to use XPConnect, a system that lets you access Mozilla's XPCOM (component library) in javascript. If you want to do this in the browser, it looks like only firefox extensions have the proper permissions to interact with those components (). If you didn't want to do this in the browser, you obviously could just use node.
Assuredly, more complications are bound to show up during implementation. But this looks like the most sure path forward, seeing as how OS.File gives you access to functions like OS.File.writeAtomic() & basic write to file
That being said, it's not that great of a path, but hopefully this gives you a solid starting point. As #dandavis mentioned, browsers (i.e. "client side logic") are designed to not allow this sort of thing. It would be an incredibly huge oversight / security flaw if a website could interact with any user's local file system.
Additional resources:
Wikipedia on XPConnect
Guide on working with XPCOM in javascript - may not be that useful
There is a way to do this, but it relies on a Chrome only Filesystem API. We will create and write to a temporary file in a sandboxed file system and the copy it to the regular file system once we are done. This way you do not have to store the entire file in memory. The asynchronous version of the Chrome API is not currently being considered for standardization by W3C, but the synchronous verison (which uses web workers) is. If browser support is a concern, then this answer is not for you.
The API works like this:
First, we get the requestFileSystem() function from the browser. Currently it is prefixed by "webkit":
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
Next, we request a temporary file system (this way we do not need to ask for user permission):
var fileSystem; //This will store the fileSystem for later access
var fileSize = 1024*1024 //Our maximum file system size.
function errorHandler(e) {
console.log('Error: ' + e.name);
}
window.requestFileSystem(window.TEMPORARY, fileSize, function (fs) { fileSystem = fs; }, errorHandler);
Now that we have access to the file system it is time to create a file:
var fileOptions = {
create: true, //If the file is not found, create it
exclusive: false //Don't throw an error if the file doesn't exist
};
Here we call the getFile() function, which can create a file if it doesn't exist. Inside of the callback, we can create a new fileWriter for writing to the file. The fileWriter is then moved to the end of the file, and we create a new text blob to append to it.
fileSystem.root.getFile(fileName, fileOptions, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.seek(fileWriter.length);
var blob = new Blob([STRING_TO_WRITE], {type: 'text/plain'});
fileWriter.write(blob);
}, errorHandler);
});
Note that this API does not save to the normal, user filesystem. Instead, it saves to a special sandboxed folder. If you want to save it to the user's file system, you can create a filesystem: link. When the user clicks on it, it will prompt them to save it. After they save it, you can then remove the temporary file.
This function generates the filesystem link using the fileEntry's toURL() function:
var save = function () {
var download = document.querySelector("a[download]");
if (!fileSystem) { return; }
fileSystem.root.getFile(fileName, {create: false, exclusive: true}, function(fileEntry) {
download.href = fileEntry.toURL();
}, errorHandler);
}
Using a link with the download attribute will force the download of the file.
<a download></a>
Here is a plunker that demonstrates this: http://plnkr.co/edit/q6ihXWEXSOtutbEy1b5G?p=preview
Hopefully this accomplishes what you want. You can continuously append to the file, it won't be kept in memory, but it will be in the sandboxed filesystem until the user saves it to the regular filesystem.
For more information take a look at this HTML5rocks article or this one if you want to use the newer, synchronous Web Worker API.
I would have suggest it the way #quantumwannabe describes it, using temporary sandbox file to append chunks.
But there is a new way that can be used today (behind a flag) but will be enabled in the next version of chrome (52)
And here is where i will make #KeenanLidral-Porter answer incorrect. And #quantumwannabe answer a unnecessary step
Because there is now a way to write a stream to the filesystem directly: StreamSaver.js
It acts as if there was a server sending octet-stream header and tells the browser to download chunks of data with help of a service worker
const writeStream = streamSaver.createWriteStream('filename.txt')
const encoder = new TextEncoder
let data = 'a'.repeat(1024) // Writing some stuff triggers the save dialog to show
let uint8array = encoder.encode(data + "\n\n")
writeStream.write(uint8array) // Write some data when you got some
writeStream.close() // End the saving
We have a program the wants to get an image copy into the clipboard to paste into a file on the HDD using javascript/HTA.
Does anyone done something like this before? Or How can I create an image file on the HDD from the information in the clipboard?
We are already using the following for text, but it does not work for images:
clipboardData.setData("Text", 'To Copy to clipboard');
clipboardData.getData("Text"); // To copy from clipboard
You can possibly read the clipboard data in some supported browsers:
Is it possible to read the clipboard in Firefox, Safari and Chrome using Javascript?
The problem is with you storing this data on the user's hard-drive. Javascript to my knowledge will not give you access to the user's hard-drive due to security reasons. One way to get around this is to send this data to a server running a php script that will then proceed to read the data and save it to the server's local storage. This php script can be set up to return the full path which was used when saving the file. Your javascript post method can then use this returned path to load it in a browser which will prompt your browser to display the download prompt. Then the user can download the file and save it to their local drive.
It very convoluted but can work.
RE: HTA
HTA only works in IE and is not very popular so you will have some problems finding code resource for the exact tasks that you require. This is some code which I found for reading and writing files to disk
<!--
// CAREFUL -- no error checking
function readFile()
{
var fso, fileHandle, contents, yourfilename;
fso = new ActiveXObject("Scripting.FileSystemObject");
fileHandle = fso.OpenTextFile(document.editor.yourfilename.value, 1);
contents = fileHandle.ReadAll();
if (contents)
document.all("fileContents").value = contents;
fileHandle.close();
}
function writeFile()
{
var fso, fileHandle, yourfilename;
fso = new ActiveXObject("Scripting.FileSystemObject");
fileHandle = fso.CreateTextFile(document.editor.yourfilename.value, true);
fileHandle.write(document.all("fileContents").value);
fileHandle.close();
}
//-->
Then you will have to combine this code to use the window.clipboardData.getData functionality for getting the stored clipboard contents. I have never done HTA so I can't give you any help with that.
It look that is impossible to paste an image from the clipboard. We ended up using via command line an external application like Minicap ( http://www.softpedia.com/get/Multimedia/Graphic/Graphic-Capture/MiniCap.shtml ).