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.
Related
I'm using the excel-as-json module (https://github.com/stevetarver/excel-as-json) and I have set it up so that it translates my .xlsx files to .json, but I now changed it so that the .xlsx is uploaded by the user in the front-end of the app.
I would like to run the convert on the uploaded Excel file, but since I am getting the user to upload it - I don't actually have a path to it, only the file object itself. So excel-as-json tells me that it cannot find the src file [Object object]
The excel as json function call is:
convertExcel(src, dst, options, callback);
What is the best way to pass the object as src? What if I store the .xlsx in my mongoDB, could I pass in its path easier then?
Not solution, but workaround: Get user to copy in path to file and use this. Based on answer from: Getting file full path when uploading file in html in firefox
Note this workaround only works for localhost
Solution I solved my issue by using a different module - sheet.js. I get the user to upload their file using an <input> tag and then use sheet.js to parse it into json, before sending it to the server where it will be stored.
I've converted an existing web application (HTML5, JS, CSS, etc.) into a Windows UWP app so that (hopefully) I can distribute it via the Windows Store to Surface Hubs so it can run offline. Everything is working fine, except PDF viewing. If I open a PDF in a new window, the Edge-based browser window simply crashes. If I open an IFRAME and load PDFJS into it, that also crashes. What I'd really like to do is just hand off the PDF to the operating system so the user can view it in whatever PDF viewer they have installed.
I've found some windows-specific Javascript APIs that seem promising, but I cannot get them to work. For example:
Windows.System.Launcher.launchUriAsync(
new Windows.Foundation.Uri(
"file:///"+
Windows.ApplicationModel.Package.current.installedLocation.path
.replace(/\//g,"/")+"/app/"+url)).then(function(success) {
if (!success) {
That generates a file:// URL that I can copy into Edge and it shows the PDF, so I know the URL stuff is right. However, in the application it does nothing.
If I pass an https:// URL into that launchUriAsync function, that works. So it appears that function just doesn't like file:// URLs.
I also tried this:
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(url).then(
function(file) { Windows.System.Launcher.launchFileAsync(file) })
That didn't work either. Again, no error. It just didn't do anything.
Any ideas of other things I could try?
-- Update --
See the accepted answer. Here is the code I ended up using. (Note that all my files are in a subfolder called "app"):
if (location.href.match(/^ms-appx:/)) {
url = url.replace(/\?.+/, "");
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(("app/" + url).replace(/\//g,"\\")).then(
function (file) {
var fn = performance.now()+url.replace(/^.+\./, ".");
file.copyAsync(Windows.Storage.ApplicationData.current.temporaryFolder,
fn).then(
function (file2) {
Windows.System.Launcher.launchFileAsync(file2)
})
});
return;
}
Turns out you have to turn the / into \ or it won't find the file. And copyAsync refuses to overwrite, so I just use performance.now to ensure I always use a new file name. (In my application, the source file names of the PDFs are auto-generated anyway.) If you wanted to keep the filename, you'd have to add a bunch of code to check whether it's already there, etc.
LaunchFileAsync is the right API to use here. You can't launch a file directly from the install directory because it is protected. You need to copy it first to a location that is accessible for the other app (e.g. your PDF viewer). Use StorageFile.CopyAsync to make a copy in the desired location.
Official SDK sample: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/AssociationLaunching
I just thought I'd add a variation on this answer, which combines some details from above with this info about saving a blob as a file in a JavaScript app. My case is that I have a BLOB that represents the data for an epub file, and because of the UWP content security policy, it's not possible simply to force a click on a URL created from the BLOB (that "simple" method is explicitly blocked in UWP, even though it works in Edge). Here is the code that worked for me:
// Copy BLOB to downloads folder and launch from there in Edge
// First create an empty file in the folder
Windows.Storage.DownloadsFolder.createFileAsync(filename,
Windows.Storage.CreationCollisionOption.generateUniqueName).then(
function (file) {
// Open the returned dummy file in order to copy the data to it
file.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (output) {
// Get the InputStream stream from the blob object
var input = blob.msDetachStream();
// Copy the stream from the blob to the File stream
Windows.Storage.Streams.RandomAccessStream.copyAsync(input, output).then(
function () {
output.flushAsync().done(function () {
input.close();
output.close();
Windows.System.Launcher.launchFileAsync(file);
});
});
});
});
Note that CreationCollisionOption.generateUniqueName handles the file renaming automatically, so I don't need to fiddle with performance.now() as in the answer above.
Just to add that one of the things that's so difficult about UWP app development, especially in JavaScript, is how hard it is to find coherent information. It took me hours and hours to put the above together from snippets and post replies, following false paths and incomplete MS documentation.
You will want to use the PDF APIs https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/PdfDocument/js
https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/PdfDocument/js/js/scenario1-render.js
Are you simply just trying to render a PDF file?
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.
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.
I need to download a file from a grid using a button in window. In order to send the filter parameters I use store.load however it doesn't download the file but it tries to read it. Is there any solution?
store.load({
params: {
startExel: parseInt(Ext.getCmp('startE').getValue())
}
});
startExel is an extra parameter in order to indicate that I want to download an Excel file.
I don't think its possible to do this by simple configuration changes. Because stores are loaded via AJAX calls.
Here is an idea for you:
Return a JSON object with file download url as the response to store load request. Not the actual file contents.
{ success = false, url='...'}
In client side handle the store load failure then identify and extract the returned url. You may have to tweak reader configuration a little.
Call window.open(url) to initiate the file download.
See this question from SO.
On the server end when returning the file include the following header:
Content-disposition: attachment