Finding number of files in directory with ajax - javascript

I am totally new to ajax. I have a URL that points to a directory on a server and I need to find a way to return the number of files in that directory. I tried both of the "up voted" responses in the link, but no luck. Does anybody have experience with this?
How to get the count of file in a directory using jquery?

At backend server you have to run any of these method depending upon your language from where you can send file count back to ajax call. However client side javascript is not capable of reading directory unless you use file api and ask user to select all files which is really not a solution.
PHP
$directory = "/dir";
$files = scandir($directory);
$num_files = count($files)-2;
NODEJS
var shell = require('shelljs');
var num_files = shell.exec("cd destinationFolder || exit; ls -d -- */ | grep 'page-*' | wc -l", { silent:true }).output;
ASP
int num_files Directory.EnumerateFiles(path, "*.*").Count()

Related

How to open a "Select folder" dialog from NodeJS (server-side, not browser)?

Why would you want to show a file/folder dialog on the server-side?
I'm building a project that is intended to be ran locally (both the Node server-side part and client-side in the browser), where I'd like to be able to select a path, add it to some list or JSON file, and then maintain some projects in it (webpack'ing, read files, serve via express, etc).
Mostly just for personal use, for now anyways.
The reason I ask to do this via Node instead of the browser is so I can somehow get around the security implications in modern browsers that prevents, upon selecting a folder, from revealing the full local folder paths on the client-side (from an <input> tag).
Not only that, but I also:
DON'T need to upload any files, or
DON'T need the list of files contained in the selected folder.
I just need:
a way to pick a folder in a user-friendly manner, and...
submit it's path to the server
(or have the server prompt for it, and store it somewhere).
Take this input tag for example:
<input id="open-project" type="file" />
This will result this type of popup, which is great for digging into folders, pasting portions of paths to quickly navigate where you need, go to your Quick Access / Favorites, etc...
But it's intended for selecting files, with no paths exposed, nothing useful to pass on to the server.
However...
If you switch it to this...
<input id="open-project" type="file" webkitdirectory directory />
You end up with this dreadful dialog box, which assumes you want to upload ALL THE FILES contained in the folder.
So it doesn't really look like <input> is the way to go.
Maybe there's an existing module that does this on the server-side? That way I could:
'Invoke' it from the client-side, via AJAX for example
which would then trigger it on the server
and then show me the folder-select prompt
Or...
Make, a... tree-view in the browser... that communicates back-and-forth with the node side to dig down the local filesystem...
Any suggestions?
I've accomplished this by spawning a child powershell process, and passing that value back up to the parent. This would only work on a Windows server, but something like this should work:
let psScript = `
Function Select-FolderDialog
{
param([string]$Description="Select Folder",[string]$RootFolder="Desktop")
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
Out-Null
$objForm = New-Object System.Windows.Forms.FolderBrowserDialog
$objForm.Rootfolder = $RootFolder
$objForm.Description = $Description
$Show = $objForm.ShowDialog()
If ($Show -eq "OK")
{
Return $objForm.SelectedPath
}
Else
{
Write-Error "Operation cancelled by user."
}
}
$folder = Select-FolderDialog # the variable contains user folder selection
write-host $folder
`
That's essentially the script that you need to prompt for folder location, then write it to the host (similar to a console.log)
then you'd need to execute this script and handle the output:
var spawn = require("child_process").spawn,child;
child = spawn("powershell.exe",psScript);
child.stdout.on("data",function(data){
console.log("Powershell Data: " + data);
});
child.stderr.on("data",function(data){
//this script block will get the output of the PS script
console.log("Powershell Errors: " + data);
});
child.on("exit",function(){
console.log("Powershell Script finished");
});
child.stdin.end(); //end input

Generate and download archive zip with java

I have a zip file download function.
This function generates the .zip files on output folder in the server and downloads it.
Everything works perfectly!
However, testing with multi-users doens't work.
If 3 users attempt to generate the file at the same time, only one response is returned with the file for download.
The other 2 users are waiting forever and there is no result (no error occurs, the ajax call never returns).
My code:
JavaScript:
$.fileDownload('\GenereteZipAction', {
httpMethod: "POST",
data: $('#formZip').serialize()
}).done(function () {
alert('Download successfully.');
$('#modalZipLoading').modal('hide');
})
.fail(function () {
alert('Error');
$('#modalZipLoading').modal('hide');
});
Java:
//get the name of user
userName = request.getParameter("user");
//get real path
String realPath = getServletContext().getRealPath("/");
//create user folder
File fileOutput = new File(realPath+"/reports/output/"+userName);
fileOutput.mkdirs();
//generete reports in the user output folder
ReportHelper helper = new ReportHelper();
helper.genereteReports(fileOutput);
//set the reponse and...
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment;filename=Relatorios.zip");
//set the cookie for $.fileDownload go to done function
response.setHeader("Set-Cookie", "fileDownload=true; path=/");
//zip output user folder
ZipHelper zipHelper = new ZipHelper ();
zipHelper.zipAllfiles(fileOutput);
//create and fill ZipOutputStream
ZipOutputStream zip = new ZipOutputStream(response.getOutputStream());
zipHelper.fillZipOutputStream(zip);
//do download
zip.flush();
//close
zip.close();
//delete folder
deleteDir(fileOutput);
My system is for more than five thousand users, so I'm sure more than two will use the report generation function at the same time.
I do not have much information of aplication server, just know it is IBM WebSphere.
I do not know if the problem is in my code, or the server that
not allowing multi-users. Every help is welcome!!!
You are most likely running into thread safety issues. This may help you: https://www.quora.com/What-does-the-term-thread-safe-mean-in-Java
ReportHelper or ZipHelper could be not thread-safe. genereteReports looks to be modifying something on the file system. I would look carefully at the code and ask yourself on each line, "what happens if something else tries to execute while my first thread is executing this line?" I would suggest looking into synchronized calls and how they work.

How to create file(.apk) from URL in Jaggery?

I have application store and applications have their url. I want to download apks from those urls to my jaggery server. Although below code(my first solution) create myApp.apk successfully, its not work properly.
First i tried to below code,
var url = "http://img.xxx.com/006/someApp.apk";
var data = get(url, {});
var file = new File("myApp.apk");
file.open("w");
file.write(data.data);
file.close();
when i print data.data value, its look like
i also tried,
var file = new File("http://img.xxx.com/006/someApp.apk");
file.saveAs("myApp.txt");
Can anyone help me?
.apk files are Android application files, and they are expected to start with PK, because they are actually zip archives!
They're not meant to be unzipped, although you can do it to see some of the application resources (but there are better ways for reverse engineering .apk files such as Apktool, if that's what you're looking for).
According to jaggery documentations, file.write is writing the String representation of the object to the file. So that's why you are getting an apk file which cannot be installed.
However you can make it work using copyURLToFile in apache commons-io java library as follows since jaggery supports java itself and all of WSO2 products have apache commons-io library in their class path.
<%
var JFileUtils = Packages.org.apache.commons.io.FileUtils;
var JUrl = Packages.java.net.URL;
var JFile = Packages.java.io.File;
var url = new JUrl("http://img.xxx.com/006/someApp.apk");
JFileUtils.copyURLToFile(url, new JFile("myApp.apk"));
print("done");
%>
Your file will be stored on $CARBON_HOME directory by default, unless you specified relative or absolute path to the file.

Get / Read Text File from URL - Javascript for After Effects

I'm used to selecting, opening and reading a text file (CSV, JSON) from my local directory. I now have access to our data feeds online but don't know how to do the same thing with a URL instead of a local file.
For a local file I simply use something like this:
var myFile = File.openDialog();
myFile.open();
myFile.read();
Is there a way to do this with a feed from a URL in javascript for AE?
Here is one of the feeds: feeds.nfl.com/feeds-rs/schedules.json
No need to save file, just one line do the trick =)
data = JSON.parse(system.callSystem('curl -s "https://path_to_json"'));
I think in After Effects the easiest way is to do a system call.
The Socket object from ExtendScript is complicated. Look at GetURLs.jsx by Rorohiko.
You need to allow your script to access the network. See this stackoverflow
# Mac Osx
var curlcmd = "curl feeds.nfl.com/feeds-rs/schedules.json > ~/Desktop/test/schedules.json";
var stdout = system.callSystem(curlcmd);
$.writeln(stdout);
var file = File("~/Desktop/test/schedules.json");
file.open();
var content = file.read();
file.close();
$.writeln(content);

How to fetch file content (basically read) a local file in javascript for UIAutomation iOS

Is there a possible way to read a local file in JavaScript.
MyFolder:
db.csv
Parse.js
Trying to fetch the contents of file db.csv in Parse.js, But in vain.
Can you share some links where I can get enough knowledge how to read a file.
Running Instruments in Xcode5, with test scripts in .js file where I have to feed in some values from a .csv file.
iOS UIAutomation, apple provides an api for running a task on the target's host.
performTaskWithPathArgumentsTimeout
Using this, we can have a bash script to printout the contents of a file that we wanted to fetch in the first case.
Bash script can be as simple as this for this requirement.
#! /bin/bash
FILE_NAME="$1"
cat $FILE_NAME
Save it as for example FileReader.sh file.
And in your automation script,
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout(executablePath,[filePath,fileName], 15);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
UIALogger.logDebug("stderr: " + result.stderr);
where in,
executablePath is where the command need to be executed.
var executablePath = "/bin/sh";
filePath is the location of the created FileReader.sh file. When executed, outputs the content to standard output (in our requirement).
[give full absolute path of the file]
fileName is the actual file to fetch contents from.
[give full absolute path of the file] In my case I had a Contents.csv file, which I had to read.
and the last parameter is the timeout in seconds.
Hope this helps others, trying to fetch contents (reading files) for performing iOS UIAutomation.
References:
https://stackoverflow.com/a/19016573/344798
https://developer.apple.com/library/iOS/documentation/UIAutomation/Reference/UIAHostClassReference/UIAHost/UIAHost.html
If the file is on the same domain as the site you're in, you'd load it with Ajax. If you're using Ajax, it's be something like
$.get('db.csv', function(csvContent){
//process here
});
Just note that the path to the csv file will be relative to the web page you're in, not the JavaScript file.
If you're not using jQuery, you'd have to manually work with an XmlHttpRequest object to do your Ajax call.
And though your question doesn't (seem to) deal with it, if the file is located on a different domain, then you'd have to use either jsonP or CORS.
And, just in case this is your goal, no, you can't, in client side JavaScript open up some sort of Stream and read in a file. That would be a monstrous security vulnerability.
This is a fairly simple function in Illuminator's host functions library:
function readFromFile(path) {
var result = target.host().performTaskWithPathArgumentsTimeout("/bin/cat", [path], 10);
// be verbose if something didn't go well
if (0 != result.exitCode) {
throw new Error("readFromFile failed: " + result.stderr);
}
return result.stdout;
}
If you are using Illuminator, this is host().readFromFile(path).

Categories

Resources