including other files besides js css etc. into html - javascript

I'm trying to read some information from a local XML document however i cant figure out how to do it.
I'm able to include js(and read data from them) css and all those kind of files but how do i read from an XML file or any other file.
The XML file is in the same directory as the js file so why shouldn't i be able to read it like any other js file?
I know it's possible to read files using nodejs but i'm trying to read the xml data and display it in a html page so it has to be client side.
// kan tijdelijk delayreport in js file zetten
var fs = require('browserify-fs'),
xml2js = require('xml2js');
var parser = new xml2js.Parser();
fs.readFile('delayReport.xml', function(err, data) {
parser.parseString(data, function (err, result) {
//console.dir(JSON.stringify(result,null,2));
console.log('Done');
console.log(result);
});
});
xhttp.open("GET", "delayReport.xml", true);

Generally it's not possible, because the XHMLRequest needs a server for asynchron communication. Only Browser that I know that loads local files offline is firefox. but maybe there are some workarounds, like discussed here xmlhttprequest for local files

Don't rely on the file:// protocol. Set up a local server and host your XML file statically through that. Then you will be able to request your XML file with an XHR. Fighting file:// is going to give you headaches.

Related

How to open a .csv (or any extension) file in plain javascript

I have a csv file and I want to open it (in excel) with plain javascript.
I've searched a lot of websites and none of them seem to have the answer.
ANSWER
const { exec } = require('child_process');
exec('start ./csv/Fixture.csv', (err, stdout, stderr) => {});
You will need to use node.js or some sort of server to deliver the payload or the csv file to a JavaScript buffer such as via a websocket. Client side browser JS is a sandbox and you need to get your data from the server, or use node.js server to write javascript that runs on the server and can access files, but I think you mean you want to access a csv file on a webpage, and to do that you would need to have server side code send it to you, by using a XHR or WebSocket transfer.
Use the new HTML anchor tag attribute, for example:
<a href="abc.csv" download> Click Here... </a>

Renaming files in a wordpress folder via jquery / jscript

I am trying to run a script that will run every 5 minutes in a shared hostings wordpress folder that will rename the newest CSV file in that folder.
/wp-content/csv/sample.csv
I tried putting a js file in the folder within that folder and run it.
var fs = require('fs');
function runClear()
{
fs.readdir("", (err, files) => {
files.forEach(file => {
console.log(file);
});
})
}
runClear();
setInterval(runClear, 300*1000);
However, it seems like I got client side and server side scripting confused. It seems like I need node.js.
What would be the best approach for this?
Regards,
Yes you are right you are confused in client side and server side script.
Javascript is a client side script which deal with all the user interactions like what will happen user click something or submit a form, hover over some element, scroll the web page etc.
Where as server side script like php deals with data stored on server like mysql records or the physical files.
what you are trying to do is to change the server resource from client side script. and you can not do that directly.
Instead you can call an ajax function which send an HTTP request to some script placed on server. And in that server script write the code to read the existing files in a directory and rename them using file handling operations.

Meteor reading csv file Papa Parse

guys I am new to Meteor. For my present application I am using openlayer so for openlayer I call Template.map.onRendered event which will load a map which has a overlay which shows marker on map and when we click on this marker an event is generated and a popup is called. Now the data to be shown in popup is hardcoded at present but I want to read it from a .csv file stored on server.
I checked online coders suggested to use Papa Parse with this code.
Papa.parse("http://example.com/file.csv", {
download: true,
complete: function(results) {
console.log(results);
}
});
My problems are:
But, I don't understand the code and how to use it to solve my
problem.
And also doing like this is safe or not in terms of browser
compatibility?
And in which folder I should save this .csv file. On internet it says private folder.
Sorry, I can't share the code using Jsfiddle as it is a private code and I am not allowed to share it.
PapaParse is mainly for client-side usage. It also has a Meteor wrapper, harrison:papa-parse, so you can try installing that as well:
meteor add harrison:papa-parse
Parse file via URL:
To parse CSV file on the server side via URL, you can try using the Parse Remote File option:
Papa.parse(url, {
download: true,
// rest of config ...
})
Parse file via CSV String:
Else you can store the file in /private folder, as it is a good option in Meteor to keep the file secure.
You can then access the file /private/file.csv using Assets.getText() method that will return a UTF-8 encoded string.
You can include the PapaParse string function in the Assets.getText() callback. After that, you can wrap the resulting function in a Meteor method, which you can call from the client using Meteor.call():
Meteor.methods({
'parseFile'() {
// read private asset as text
Assets.getText('/private/file.csv', (error, result) => {
if(error) {
return console.log(error);
}
// 'result' should be a UTF-8 string,
// parse it using PapaParse string function
return Papa.parse(result)
});
}
});
See if that works, read the documentation for more details.
If it doesn't work, check to see if you can read the source file at all on server-side. Often, it turns out to be a relative path error.
Alternative: BabyParse
You can also try to use the PapaParse Node.js fork called BabyParse, available on NPM. However, it cannot read files, only strings. So you will first have to read the CSV file via Assets.getText() and convert it into a CSV string. You can then feed the CSV string into BabyParse to get your result.

How to load the contents of a local text file by name using Javascript and HTML 5?

Working in Chrome, loading a local html or JS file.
I found many examples of how to load a file that is selected using the Choose File input.
However, didn't figure out how to do it given a file name without using the Choose File input.
The Choose File input returns a File object.
How to create the File object without the Choose File input?
From the File API:
new File(
Array parts,
String filename,
BlobPropertyBag properties
);
But didn't figure out what the parts and properties would be.
Edit: Use case:
I have code coverage results generated as part of a test suite. It is stored as JSON (which is easy to read), but I need to display it with the source code.
So the feature is to load the source code and JSON data, and render them together on a web page using HTML and Javascript.
The file would be opened from the browser and lives on the local machine. There is no server.
The browser cannot load arbitrary files by name from your filesystem without special extensions or other shenanigans. This is a security policy to prevent random web sites from reading files from your hard disk as you browse the internet.
If you're down to do something special like if you want to write a chrome app, you could get access to some nice APIs for accessing the filesystem:
https://developer.chrome.com/apps/fileSystem
The File constructor doesn't read a file from the harddrive, but rater make a virtual file, consider this:
var file = new File(["some", "content"], "/tmp/my-name.txt");
var reader = new FileReader();
reader.onload = function() {
console.log(reader.result); // somecontent
};
No file will be read or stored on the clients machine.
If you are talking about creating files in nodejs then you should take a look at fs.
For security reasons all browsers don't support predefined values on file fields so the answer is you can't.

Downloading a file to the file system in WinJS

We are developing an app that is to download files from HTTP URLs, the extensions/file types of which we will not know until runtime. We've been following this tutorial as a starting point, but since we aren't dealing with images, it hasn't helped us.
The issue is that the code in the tutorial will get you a Blob object and I can't find any code that will allow us to either:
Convert the Blob to a byte array.
Save the Blob straight to the file system.
The ultimate goal is to seamlessly save the file at the given URL to the file system and launch it with the default application, or to just launch it from the URL directly (without the save prompt you get if you just call Windows.System.Launcher.launchUriAsync(uri);).
Any insight anyone might have is greatly appreciated.
Regarding downloading content into byte array:
Using WinJS.xhr with the responseType option as 'arraybuffer' will return the contents in ArrayBuffer. A javascript typed array can be instantiated from the ArrayBuffer for example UInt8Array. This way contents can be read into byte array. code should look something like this:
// todo add other options reqd
var options = { url: url, responseType: 'arraybuffer' };
WinJS.xhr(options).then(function onxhr(ab)
{
var bytes = new Uint8Array(ab, 0, ab.byteLength);
}, function onerror()
{
// handle error
});
Once you take care of permissions to save the file to file system either by user explicitly picking the save file location using SaveFilePicker or pick folder using folder picker - file can be saved on local file system. Also, file can be saved to app data folder.
AFAIK, html/js/css files from local file system or the app data cannot be loaded for security reasons. Although DOM can be manipulated under constraints, to add content. I am not sure of your application requirements. You might need to consider alternatives instead of launching downloaded html files.

Categories