Find most recent JSON file in a server directory - javascript

I can't really match an answer to this issue so I've decided to post this question hoping to find a solution.
I would like to use preferably JQuery / javascript or even PHP to find the most recent JSON files in a specified directory.
Why I would like to do this? Because when a user of my html5/javascript webapplication saves some array of objects to a JSON file, then besides the original work JSON file, there is a backup file that is created with a random name and which is the exact copy of the original JSON file.
If something happens to the original JSON file I would like the user to be able to open the most recent backup files from the backups directoy and select the right one to be recovered.
To open a JSON file I usually use this code:
$.getJSON('main/backups/random1345004.json', function(info){ ... });
Now the trouble is that in case of a backup I don't know the name of the JSON file that should be opened, because each file is unic and has a Math.random() generated name when it's created.
So I repeat the question: Is there a way to open from the backups directory the most recently created, randomly named, JSON files?
If not I might try to use .getTime() javascript method instead of Math.random() to control the names of the backup files created and then use a loop to search for a valid backup file name. That's a hunch, but I would not like to make anything stupid if there is a better solution, without loops.
Security is not a concern for me at this rate.
Thank you for any help provided!

If your server supports WebDav or FTP on your main\backups folder then you could search for all files greater today and then select the more recent.
--- Addition ---
With PHP, take a look at sort files by date in PHP

You could replace your $.getJSON() call with a standard ajax request:
<script>
$.ajax({
url : "getMostRecentBackup.php",
datatype : "json"
})
.done(function(data){
console.log( data.toSource() );
})
.fail(function() {
alert( "error" );
});
</script>
getMostRecentBackup.php will read backup directory and return a JSON object containing the most recent backup file, please read this Topic: sort files by date in PHP

Related

How to create javascript File object for local CSV file to read in and convert to JSON?

I am working in ReactJS, my app is currently running locally with Create React App. I have a .csv file in my project src folder that I need to read in and convert to an array of javascript objects using Papaparse, but can't figure out how to create a File object to pass into the Papa.parse() method. The File documentation seems to all refer to creating a new file or reading a file passed by a user through drag and drop, etc. I can't find a reference to creating a File by pathname. I was previously successfully reading a json file stored in the same place in the src folder, but now need to switch to reading csv and converting to array of JS objects. There is no problem with the formatting of the .csv, I copied several lines of it as a multiline string and it was correctly parsed to json with Papa.parse(), but I don't understand how to pass in a File.
You are dealing with data on your server, not data the user is picking from a file <input>. Use URLs, not File objects.
You need to give the CSV file a URL (how you do that depends on the particular server you are using, this question seems to cover it if you are using the Webpack development server).
Then you need to pass that URL a per the documentation to Papa Parse.
Papa.parse("http://example.com/file.csv", {
download: true,
complete: function(results) {
console.log(results);
}
});

Read local .json from local .js without repos

I'm trying to write a chrome-extension that closes tabs when they're loaded and their links contain specific keywords, which I've saved in a .json file. Because the content.js has no access on the browser peripherals, I had to use the background.js script to close the tab. So far the extension does all that except loading the data from the .json, which means that I had to write the json (just for testing) into the background.js. Because I want to ban a lot of links this is'nt an option for me. So I decided on storing a list with the links in a .json file, which is stored in the same folder as the background.js, which means that it's on the localhost and not on any kink of webserver. That means that it should be possible to access this file, because after my research, I came to the assumption that the background.js runs on the localhost as well. So there should'nt occur any file accessing limitation issues right?
Unfortuantely I've got no idea how to write this in pure .js, because all the tutorials or posts here are either accessing the file from or in a webserver or using some kind of fancy library. This should be possible without one right?
chrome.webNavigation.onCompleted.addListener(closeTab, {
url: [
{urlPrefix: 'https://www.google.de/'},
{urlPrefix: 'https://sghm.eu/iserv/login'},
]
});
function closeTab(e) {
if (!e.frameId) {
chrome.tabs.remove(e.tabId);
}
}
this is how my code looks now, I want to have some kind of loadData('data.json') function that returns the .jsons content, so that I can delete this whole .json data strucure within the js.
It should be possible to access the javascript object notation language via javascript.
I personally think you can do this far easier and faster with using Chrome.storage. The data is saved as a json object and easy to reference and it sounds like exactly what you need as you're just referencing key/pair values anyway.

Parse CSV from URL into Array using Javascript

I'm relatively new to javascript but I want to get some data from a csv file that is saved online and gets updated each hour.
The data should be displayed on a table later on but I have some problems with saving it to an array. The csv file is comma seperated, has 9 columns, over 6000 rows and is a long string of text, so no linebreaks. The first row contains usernames and each username with special characters is conclosed with quotation marks.
I've tried several codes over the past few days, but none worked. Can I parse a online CSV file into an array at all? Is there an alternative like with SQL or saving the file to my server?
Remember: The file gets updated each hour..
NOTE: There are not really problems with the codes I've found, all of these were tested by others and seemed to work. But only for local files, not actual URLs!
You can use this https://code.google.com/p/jquery-csv/ plugin and it is possible to convert multi-line csv into 2D-array using $.csv.toArrays(csv) or to an object using $.csv.toObjects(csv). Check this post or this one for more info
$.ajax({
url: "urlto/filename.csv",
success: function (data) {
var arr = $.csvtoArray(data);
_oncomplete(arr);
},
dataType: "text",
});
_oncomplete: function (arr) {
//Your array here
}
You can have a look at papaparse for a solid and full-featured CSV parsing library.
setInterval javascript function lets you update the data every hour, in case you decide to develop this part on the client.
Is there an alternative like with SQL or saving the file to my server?
Yes there are alternatives, the right architecture depends on your use case. How many visitors will go to your web page and view the results, how critical your application is, how reliable the data source is, etc. If you're not sure about these you should talk to a web developer with more experience around these questions.
You may want to parse the CSV file every hour on the server and store a copy of the data there, to serve to your visitors. This way, if the upstream data source is unavailable, you still have a copy of the data from the past.
P.S.:
I've tried several codes over the past few days, but none worked
stackOverflow is about this: getting help about specific problems in your code, rather than asking general questions (answer to those can be found easily using a search engine).

Generate a Word document in JavaScript with Docx.js?

I am trying to use docx.js to generate a Word document but I can't seem to get it to work.
I copied the raw code into the Google Chrome console after amending line 247 to fix a "'textAlign' undefined error"
if (inNode.style && inNode.style.textAlign){..}
Which makes the function convertContent available. The result of which is an Object e.g.
JSON.stringify( convertContent($('<p>Word!</p>)[0]) )
Results in -
"{"string":
"<w:body>
<w:p>
<w:r>
<w:t xml:space=\"preserve\">Word!</w:t>
</w:r>
</w:p>
</w:body>"
,"charSpaceCount":5
,"charCount":5,
"pCount":1}"
I copied
<w:body>
<w:p>
<w:r>
<w:t xml:space="preserve">Word!</w:t>
</w:r>
</w:p>
</w:body>
into Notepad++ and saved it as a file with an extension of 'docx' but when I open it in MS Word but it says 'cannot be opened because there is a problem with the contents'.
Am I missing some attribute or XML tags or something?
You can generate a Docx Document from a template using docxtemplater (library I have created).
It can replace tags by their values (like a template engine), and also replace images in a paid version.
Here is a demo of the templating engine: https://docxtemplater.com/demo/
This code can't work on a JSFiddle because of the ajaxCalls to local files (everything that is in the blankfolder), or you should enter all files in ByteArray format and use the jsFiddle echo API: http://doc.jsfiddle.net/use/echo.html
I know this is an older question and you already have an answer, but I struggled getting this to work for a day, so I thought I'd share my results.
Like you, I had to fix the textAlign bug by changing the line to this:
if (inNode.style && inNode.style.textAlign)
Also, it didn't handle HTML comments. So, I had to add the following line above the check for a "#text" node in the for loop:
if (inNodeChild.nodeName === '#comment') continue;
To create the docx was tricky since there is absolutely no documentation on this thing as of yet. But looking through the code, I see that it is expecting the HTML to be in a File object. For my purposes, I wanted to use the HTML I rendered, not some HTML file the user has to select to upload. So I had to trick it by making my own object with the same property that it was looking for and pass it in. To save it to the client, I use FileSaver.js, which requires a blob. I included this function that converts base64 into a blob. So my code to implement it is this:
var result = docx({ DOM: $('#myDiv')[0] });
var blob = b64toBlob(result.base64, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
saveAs(blob, "test.docx");
In the end, this would work for simple Word documents, but isn't nearly sophisticated for anything more. I couldn't get any of my styles to render and I didn't even attempt to get images working. I've since abandoned this approach and am now researching DocxgenJS or some server-side solution.
You may find this link useful,
http://evidenceprime.github.io/html-docx-js/
An online demo here:
http://evidenceprime.github.io/html-docx-js/test/sample.html
You are doing the correct thing codewise, but your file is not a valid docx file. If you look through the docx() function in docx.js, you will see that a docx file is actually a zip containing several xml files.
I am using Open Xml SDK for JavaScript.
http://ericwhite.com/blog/open-xml-sdk-for-javascript/
Basically, on web server, I have a empty docx file as new template.
when user in browser click new docx file, I will retrieve the empty docx file as template, convert it to BASE64 and return it as Ajax response.
in client scripts, you convert the BASE64 string to byte array and using openxmlsdk.js to load the byte array as an javascript OpenXmlPackage object.
once you have the package loaded, you can use regular OpenXmlPart to create a real document. (inserting image, creating table/row ).
the last step is stream it out to end user as a document. this part is security related. in my code I send it back to webserver and gets saved temporarily. and prepare a http response to notify end user to download it.
Check the URL above, there are useful samples of doing this in JavaScript.

HTML5 with javascript to parse and display textfile

I have an HTML5 page (index.html), and I need to display the contents of a .txt file (p001wide.txt). Both are on the server in the same directory.
The text file is generated from a CMS, so I cannot change the format of that file.
In the .txt file is a variable named widetxt. I need to display the contents of the widetxt variable on the page.
What do I need to do to parse the the textfile and display it in the HTML page?
Do I need to use javascript, and if so, how?
Hm, I found this question which appears to be similar to yours as far as reading a file goes. As for parsing though why not use a database such as MySQL to store your data? This way you can quickly add and query through your data.
As both your index file and the text file you wish to read reside on the server you should be able to read the text file on the server and insert what you wish from it into the index file using PHP.
See http://www.w3schools.com/php/php_file.asp for a tutorial on how that can be done without resorting to client side script.
If you cannot alter your index file on the server and can put a PHP file on the server you can use AJAX to ask your PHP file to read the contents of the text file and return it to you. Then you would use javascript to insert it as you wish. I presume that you can alter the index file because otherwise you could not alter its javascript either.
You can do this with JavaScript, you basically need to learn how to read and write files (and you mention the variable inside, this would be parsing). Start reading here - http://www.c-point.com/JavaScript/articles/file_access_with_JavaScript.htm other information, just Google read write files javascript, or parsing text with javascript.
Best of luck!

Categories