I am trying to open multiple images simultaneously in the default Windows Photo Viewer that I have stored in my folder using the npm open library:
let files = ['Dog.gif', 'Cat.jpeg'];
for(let i=0; i<files.length; i++){
open(`${files[i]}`, {wait:true});
}
But it's only opening the first file? I am not sure how to fix this?
in my case, it happened because the file name or file type did not exist or did not match the source file
{wait: true} is supposed to cause open() to wait until you exit the application that opens the file before resuming execution. So if you expect them all to open at the same time, remove the {wait: true} option.
If you, in fact, do want it to wait until the application exits before opening the second file and hare having it only open one file, read on for at least some minimal debugging help.
Assuming you are using a recent version of open, it is a promise-based API. It seems to make it hard to get at errors. However, you can at least confirm that you're getting an error like this:
const open = require('open');
let files = ['dog.txt', 'cat.txt'];
(async () => {
for(let i=0; i<files.length; i++){
const cp = await open(`${files[i]}`, {wait: true});
console.log(`${files[i]} exit code: ${cp.exitCode}`);
}
})();
That will print an error code of 0 for all files where open() succeeded and a non-zero value for all files where open() failed.
Related
I'm trying to upload files in WordPress using admin-ajax.php
I have this code in my functions.php file
function upload_docs(){
var_dump($_FILES);
}
add_action('wp_ajax_nopriv_upload_docs', 'upload_docs');
add_action('wp_ajax_upload_docs', 'upload_docs');
The function at the moment is a test that I want to use to debug what information is passed from the front-end which is a Vue app hosted in a page template.
I've correctly loaded and localized the Vue CSS and js files and after the build, in my localhost, I'm able to pass the other forms I have configured on my functions file
On the front-end side, the Vue app has this method that will add the needed information to the WordPress backend
sendUploadForm(){
let documents = this.$refs.uploadedFiles.files
let userData = new FormData()
for(let i = 0; i < documents.length; i++ ){
userData.append('file[]', documents[i])
}
userData.append('action', 'upload_docs')
axios.post(wp_param.ajaxurl, userData).then( res => {
console.log(res)
}).catch( e => console.log(e) )
}
What is going wrong with the code? I will always get a 500 error status code ERR_BAD_RESPONSE and I don't know if the function is called because I'm unable to see any var_dump or var_export from PHP. I've tried to enable the debug in wp-config file but nothing changed.
Any suggestion?
Add these additional two lines under your WP_DEBUG one, make the error happen again, and check in the folder wp-content/ if you see a new file debug.log.
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
Consider:
Implementing nonces and permission checks to protect your endpoints
If only logged in users are supposed to be able to upload files, ensure the no_priv method is properly locked down
Using a custom REST API endpoint instead of admin-ajax https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/
Terminate your function with wp_die(); when using AJAX in WordPress
I was stuck with this problem because of WordPress plugin conflicts.
You can disable unused plugins and check.
I'm a new developer and this is my first Stack Overflow post. I've tried to stick to the format as best as possible. It's a difficult issue for me to explain, so please let me know if there's any problems with this post!
Problem
I'm working on a vscode extension specifically built for Next.js applications and running into issues on an event listener for the onDidChangeText() method. I'm looking to capture data from a JSON file that will always be located in the root of the project (this is automatically generated/updated on each refresh of the test node server for the Next.js app).
Expected Results
The extension is able to look for updates on the file using onDidChangeText(). However, the issue I'm facing is on the initial run of the application. In order for the extension to start listening for changes to the JSON file, the user has to be in the JSON file. It's supposed to work no matter what file the user has opened in vscode. After the user visits the JSON file while the extension is on, it begins to work from every file in the Next.js project folder.
Reproducing this issue is difficult because it requires an extension, npm package, and a next.js demo app, but the general steps are below. If needed, I can provide code for the rest.
1. Start debug session
2. Open Next.js application
3. Run application in node dev
4. Do not open the root JSON file
What I've Tried
Console logs show we are not entering the onDidTextDocumentChange() block until the user opens the root JSON file.
File path to the root folder is correctly generated at all times, and prior to the promise being reached.
Is this potentially an async issue? Or is the method somehow dependent on the Active Window of the user to start looking for changes to that document?
Since the file is both created and updated automatically, we've tested for both, and neither are working until the user opens the root JSON file in their vscode.
Relevant code snippet (this will not work alone but I can provide the rest of the code if necessary. ).
export async function activate(context: vscode.ExtensionContext) {
console.log('Congratulations, your extension "Next Step" is now active!');
setupExtension();
const output = vscode.window.createOutputChannel('METRICS');
// this is getting the application's root folder filepath string from its uri
if (!vscode.workspace.workspaceFolders) {
return;
}
const rootFolderPath = vscode.workspace.workspaceFolders[0].uri.path;
// const vscode.workspace.workspaceFolders: readonly vscode.WorkspaceFolder[] | undefined;
// this gives us the fileName - we join the root folder URI with the file we are looking for, which is metrics.json
const fileName = path.join(rootFolderPath, '/metrics.json');
const generateMetrics = vscode.commands.registerCommand(
'extension.generateMetrics',
async () => {
console.log('Succesfully entered registerCommand');
toggle = true;
vscode.workspace.onDidChangeTextDocument(async (e) => {
if (toggle) {
console.log('Succesfully entered onDidChangeTextDocument');
if (e.document.uri.path === fileName) {
// name the command to be called on any file in the application
// this parses our fileName to an URI - we need to do this for when we run openTextDocument below
const fileUri = vscode.Uri.parse(fileName);
// open the file at the Uri path and get the text
const metricData = await vscode.workspace
.openTextDocument(fileUri)
.then((document) => {
return document.getText();
});
}
}
});
});
}
Solved this by adding an "openTextDocument" call inside the "registerCommand" block outside of the "onDidChangeTextDocument" function. This made the extension aware of the 'metrics.json' file without it being open in the user's IDE.
I have an Electron app. It sends via a ipcRenderer.send in renderer.js a download event to an ipcMain.on listener in index.js:
renderer.js:
for (var i=0; i < data3.projects.length; i++) {
var project = data3.projects[i];
for (var j=0; j < project.files.length; j++) {
var file = project.files[j];
async function downloadFunction(file) {
await ipcRenderer.send("download", {
url: file.url,
location: "/Users/Marc/GreenPool/" + project.projectId + "/files/"
})
console.log("downloaded " + file.url);
}
await downloadFunction(file);
}
}
index.js:
ipcMain.on("download", function (event, info) {
console.log(info.location);
download(mb.window.webContents, info.url, {directory:info.location});
});
So it is supposed to download (thanks to electron-dl npm package) all the files under project.files, and save them under info.location.
When there is only one project under data3.projects array, it works, the files get downloaded and stored under "/Users/Marc/GreenPool/" + project.projectId + "/files/".
But when there is more than one value in data3.projects array, it only saves the downloaded files of one of the data3.project, not of the others:
One has the files:
One doesn't:
We can see on the first picture that one of the files is duplicated. I think it shows that the issue has to do with the fact that after writing the first files in the first folder, it somehow still thinks that it is in this one when starting to write the second files (we can see it with file compute2Numbers(1).js being a duplicate because it is in the wrong folder).
And the log of console are logic:
index.js:
/Users/Marc/GreenPool/qjggnatri/files/
/Users/Marc/GreenPool/qjggnatri/files/
/Users/Marc/GreenPool/qjggnatri/files/
/Users/Marc/GreenPool/qjggnatri/files/
/Users/Marc/GreenPool/z9g7_a1qa/files/
/Users/Marc/GreenPool/z9g7_a1qa/files/
/Users/Marc/GreenPool/z9g7_a1qa/files/
/Users/Marc/GreenPool/z9g7_a1qa/files/
renderer.js:
It seems like it is an asynchronous issue. But I have wrapped the queries in an async await function to prevent the two download events from overlapping each other. And the logs of the console show it: first the files of the first value in data3.projects array are downloaded, then the files of the second value in data3.projects array are downloaded.
So how can I make it happen that the files get saved in the proper folder?
In Chrome 32, I've got an JS app where I write raw images from a canvas to a file and I want to close the file and open it for processing in a worker.
I pass the file name to the worker and I can see that it's found and opened but as soon as I try to read it I get a DOM exception (NotFoundError).
// In my worker:
fs = self.requestFileSystemSync(self.PERSISTENT, quota);
var f = fs.root.getFile(rawFileName, {create: false}); // this works, f is valid
var reader = new FileReaderSync();
// At this point, 'reader' looks ok
rawFramesArrayBuffer = reader.readAsArrayBuffer(f); // My exception is thrown here.
log("Opened " + rawFileName + " for reading.");
In my main thread, I've tried setting my File and FileWriter to undefined to ensure the file is closed (I can't see a method for doing this), but it doesn't help. In any event, the spec says that a NotReadableError should be thrown if the file is locked, but I don't see this.
If I step through the code, everything pauses for about 5 seconds when I step over the readAsArrayBuffer line and then the NotFoundError is thrown.
If I create a DirectoryReader and enumerate all the files, I can see that my file exists.
You may want to pass the images to the worker rather than saving them and having the worker open a file.
Here is a page with sample code
http://kinderas.blogspot.com/2011/06/html-5-web-workers-and-image-processing.html
But it does depend on how big your image is.
I found this interesting but haven't tried to do processing from the computer camera so it may help you out.
http://blog.aviary.com/posts/live-image-processing-with-getusermedia-and-web-workers
I needed to access the file via the FileEntry:
rawFramesArrayBuffer = reader.readAsArrayBuffer(f.file());
Summary
I am attempting to find out why the wl.download function will not download more than one file even though the Microsoft examples seem to indicate that they can.
And, the code seems to be called for each file you attempt to download, but only the one file is actually downloaded.
Details
Here are the details of how you can see this problem which I've tried in IE 11.x and Chrome 30.x
If you will kindly go to :
http://isdk.dev.live.com/dev/isdk/ISDK.aspx?category=scenarioGroup_skyDrive&index=0
You will be able to run an example app which allows you to download files from your skydrive.
Note: the app does require you to allow the app to access your skydrive.
Once you get there you'll see code that looks like this on the right side of the page:
Alter One Value: select:
You need to alter one value: Change the
select: 'single'
to
select: 'multi'
which will allow you to select numerous files to download to your computer. If you do not make that one change then you won't be able to choose more than one file in the File dialog.
Click the Run Button to Start
Next, you'll see a [Run] button to start the app (above the code sample).
Go ahead and click that button.
Pick Files For Download
After that just traverse through your skydrive files and choose more than one in a folder and click the [Open] button. At that point, you will see one of the files actually downloads, and a number of file names are displayed in the bottom (output) section of the example web page.
My Questions
Why is it that the others do not download, even though wl.download is called in the loop, just as the console.log is called in the loop?
Is this a known limitation of the browser?
Is this a known bug in skydrive API?
Is this just a bug in the example code?
The problem here is that the call to wl.download({ "path": file.id + "/content" }) stores some internal state (among other things, the file being downloaded and the current status thereof). By looping over the list of files, that state is in fact overwritten with each call. When I tried downloading three text files at once, it was always the last one that was actually downloaded and never the first two.
The difficulty here is that the downloads are executed in the traditional fashion, whereby the server adds Content-Disposition: attachment to the response headers to force the browser to download the file. Because of this, it is not possible to receive notification of any kind when the download has actually completed, meaning that you can't perform the downloads serially to get around the state problem.
One approach that I thought might work is inspired by this question. According to the documentation, we can get a download link to a file if we append /content?suppress_redirects=true to its id. Using this approach, we can set the src property of an IFrame and download the file that way. This works OK, but it will only force a download for file types that the browser can't natively display (zip files, Exe files, etc.) due to the lack of the Content-Disposition: attachment response header.
The following is what I used in the Interactive Live SDK.
WL.init({ client_id: clientId, redirect_uri: redirectUri });
WL.login({ "scope": "wl.skydrive wl.signin" }).then(
function(response) {
openFromSkyDrive();
},
function(response) {
log("Failed to authenticate.");
}
);
function openFromSkyDrive() {
WL.fileDialog({
mode: 'open',
select: 'multi'
}).then(
function(response) {
log("The following file is being downloaded:");
log("");
var files = response.data.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
log(file.name);
WL.api({
path: file.id + "/content?suppress_redirects=true",
method: "GET"
}).then(
function (response) {
var iframe = document.createElement("iframe");
iframe.src = response.location;
iframe.style.display = "none";
document.body.appendChild(iframe);
},
function (responseFailed) {
log("Error calling API: " + responseFailed.error.message);
}
);
}
},
function(errorResponse) {
log("WL.fileDialog errorResponse = " + JSON.stringify(errorResponse));
}
);
}
function log(message) {
var child = document.createTextNode(message);
var parent = document.getElementById('JsOutputDiv') || document.body;
parent.appendChild(child);
parent.appendChild(document.createElement("br"));
}
Did you try to bind some events to the WL.download() method? According to the documentation:
The WL.download method accepts only one parameter:
The required path parameter specifies the unique SkyDrive file ID of the file to download.
If the WL.download method call is unsuccessful, you can use its then method's onError parameter to report the error. In this case, the WL.download doesn't support the onSuccess and onProgress parameters. If the WL.download method call is successful, the user experience for actually downloading the files will differ based on the type of web browser in use.
Perhaps you are getting some errors in your log to identify the problem.
For me, one suggestion without having checked the documentation, I can think of the fact that you are not waiting for each download to end. Why not change your loop in such a manner that you call WL.download() only if you know no other download is currently running ( like calling the next WL.download only in the success/complete event ):
WL.download({ "path": file.id + "/content" }).then(
function (response) {
window.console && console.log("File downloaded.");
//call the next WL.download() here <!-----------------
},
function (responseFailed) {
window.console && console.log( "Error downloading file: " + responseFailed.error.message);
}
);