Is there anyway to copy/upload/edit a file with javascript? - javascript

I have two servers, Server1 & Server2. I want to copy a file from Server1 to Server2 with JavaScript. Is this possible? If so, how?
For example, last week I used "wget" command for this action. Now I want to handle it with JS.

i don't know the full specifications for the task at hand, but you could look into using Node.js to assist with your issue. here's a quick repo that might help repo or you could use this snippet i took from similar post:
var http = require('http');
var fs = require('fs');
var google = http.createClient(80, 'www.google.com');
var request = google.request('GET', '/',
{'host': 'www.google.com'});
request.end();
out = fs.createWriteStream('out');
request.on('response', function (response) {
response.setEncoding('utf8');
response.on('data', function (chunk) {
out.write(chunk);
});
});
i hope this helps, and here's the original post

Nope. You can't access disk from JavaScript. Just for a moment think of security problems it can bring with itself. I simply create a web page, and when you visit it, I upload all the images of your girlfriend and publish them (just kidding, but that's the security problem it poses).
However, JavaScript can access files on some scenarios:
When user selects some files using <input type='file' /> element
Using HTML5's offline-storage (I guess this one, not sure).
However, if you want, you can use Node.js to do that. However, this is a server-side stuff.

Related

cant write to a text file with javascript. (Uncaught ReferenceError: require is not defined at HTMLButtonElement)

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.

How do I let user save a file and keep editing that file in browser Javascript only?

I believe it would not be possible due to security reason as stated in many other articles on StackOverflow. However, when I use the Diagram app at https://app.diagrams.net/ I realized they could ask me to save a file, and somehow keep that file reference and whenever I click Save on the app, my local file on hard drive changes (no new download).
I know it's only possible to upload/download a file and believe you cannot edit it (using Blob with FileReader etc). How do they achieve that? The app is open source but unfortunately plowing through the source code of their File Handler I still cannot find out what API they are using. I don't remember installing any plugin or app in my browser.
I also notice there is this permission in my browser so I guess it's some standard API, but even using that as keyword, all leads back to StackOverflow articles saying it's not possible.
Is it a new API I am not aware of? What am I looking for?
You can use localStorage to achieve this without needing any other permission from the user.
localStorage.setItem("data", JSON.stringify(data));
If your data is just JSON then this would work, however if you have custom data types, you can take a look here.
Edit:
Since you wanted to save the file directly to the device and edit it, you can take a look at File System Access API. This article here explains it.
You can load the file first by using,
let fileHandle;
butOpenFile.addEventListener('click', async () => {
[fileHandle] = await window.showOpenFilePicker();
const file = await fileHandle.getFile();
const contents = await file.text();
textArea.value = contents;
});
Once you have the file handle you should be able to write to the file without requesting to download a new file everytime there is a change.
async function writeFile(fileHandle, contents) {
// Create a FileSystemWritableFileStream to write to.
const writable = await fileHandle.createWritable();
// Write the contents of the file to the stream.
await writable.write(contents);
// Close the file and write the contents to disk.
await writable.close();
}
The codes are from the article I have linked above and the article explains everything much clearly. It's worth reading.

Is it possible to download an html file from a given webpage using my local network/browser as if I downloaded it myself with javascript or nodejs?

I’m a bit new to javascriipt/nodejs and its packages. Is it possible to download a file using my local browser or network? Whenever I look up scraping html files or downloading them, it is always done through a separate package and their server doing a request to a given url. How do I make my own computer download a html file as if I did right click save as on a google chrome webpage without running into any server/security issues and errors with javascript?
Fetching a document over HTTP(S) in Node is definitely possible, although not as simple as some other languages. Here's the basic structure:
const https = require(`https`); // use http if it's an http url;
https.get(URLString, res => {
const buffers = [];
res.on(`data`, data => buffers.push(data));
res.on(`end`, ()=>{
const data = Buffer.concat(buffers);
/*
from here you can do what you want with the data. You can write it to a file
with fs, you can console.log it using data.toString(), etc.
*/
});
})
Edit: I think I missed the main question you had, give me a sec to add that.
Edit 2: If you're comfortable with doing the above, the way you access a website the same way as your browser is to open up the developer tools (F12 on Chrome) go to the network tab, find the request that the browser has made, and then using http(s).get(url, options, callback), set the exact same headers in the options that you see in your browser. Most of the time you won't need all of them, all you'll need is the authentication/session cookie.

download file to local computer sent attatched to message discord

after looking on the Discord.js docs i can find an answer for the question, does someone know how to do it? theres already a question the page but has no answers or comments.
imagine that someone on the chat sentí an image, is there a way of the bot downloading the image or get the url of the image?
thanks!
For starters... You'd need the code to access the attachment.
client.on(`message`,function(msg){
if(msg.attachments.first()){//checks if an attachment is sent
if(msg.attachments.first().filename === `png`){//Download only png (customize this)
download(msg.attachments.first().url);//Function I will show later
}
}
});
Note: I limited attachments to png only so we download verified images. Otherwise we might download some bad scripts and possibly viruses. Be careful when downloading stuff.
Now the code I just gave you calls download and passes in the url.
Now you will need the request module AND the fs module.
Why? Glad you asked... The request module accesses the url and pulls it the data from the web.
The fs module create/reads/writes files on your local/external machine...
Using the two modules, we will pull it and then save it.
Now lets assume url is this meme.png (discord png attachment)
let request = require(`request`);
let fs = require(`fs`);
function download(url){
request.get(url)
.on('error', console.error)
.pipe(fs.createWriteStream('meme.png'));
}
and Voila! We now have a meme.png image about Doritos XD
Besides the link I posted in the comments section, from looking at the Discord documentation, it appears the url is in the attachment object.

Get real path instead of 'fakepath' in file upload

I face the following problem:
When a user uploads a file with the HTML file input and I then want to receive the file path itself. I only get C:/fakepath/filename.txt for example.
I understand that it is a security reason for browsers to know the exact path of the file. So i was wondering if it is even possible with some hack, some way in .net or with additional jquery/js plugin to get the full path of the file.
Why?
We dont want to upload the file itself to our server filesystem, neither to the database. We just want to store the local path in the database so when the same user opens the site, he can click on that path and his local file system opens.
Any suggestions or recommendations for this approach?
If this is really not possible like
How to resolve the C:\fakepath?
How To Get Real Path Of A File Using Jquery
we would need to come up with a diffrent idea I guess. But since some of the answers are really old, I thought maybe there is a solution to it by now. Thx everyone
As my goal was to make the uploaded file name visible to the End User and then send it via php mail() function, All I did to resolve this was:
in your js file
Old function:
var fileuploadinit = function(){
$('#career_resume').change(function(){
var pathwithfilename = $('#career_resume').val();
$('.uploadedfile').html("Uploaded File Name :" + pathwithfilename).css({
'display':'block'
});
});
};
Corrected function:
var fileuploadinit = function(){
$('#career_resume').change(function(){
var pathwithfilename = $('#career_resume').val();
var filename = pathwithfilename.substring(12);
$('.uploadedfile').html("Uploaded File Name :" + filename).css({
'display':'block'
});
});
};
$(document).ready(function () {
fileuploadinit();
});
Old result:
Uploaded File Name :C:\fakepath\Coverpage.pdf
New result:
Uploaded File Name :Coverpage.pdf
Hope it helps :)
You can't do it.
And if you find a way, it's big security vulnerability that the browser manufacturer will fix when discovered.
You'll need your own code running outside browser-box to do this, since browsers are designed NOT to allow this.
I mean something ugly like ActiveX, flash, COM object, custom browser extenstion or other fancy security breach that can open it's own OpenFileDialog and insert that value in your input field.

Categories