How to get the executed javascript file directory? - javascript

I have a javascript file in a directory like:
/httpdocs/wp-content/themes/themeName/users/js
And there are some PHP files I want to make Ajax Requests to in this directory:
/httpdocs/wp-content/themes/themeName/users
How to get the PHP files directory in Javascript/Jquery?

If you have a file referenced (say, in <head>) on your page
<head>
<script src="~/httpdocs/wp-content/themes/themeName/users/js/test-file.js"></script>
</head>
you can pass the file name (without the .js extension) into this function, together with it's folder name, and it should return the path with the folder name removed:
$(function () {
var getFilePath = function (fileName, scriptFolderName) {
var reg = new RegExp("" + fileName + ".*\\.js");
var regReplace = new RegExp("/" + scriptFolderName + "/" + fileName + ".*\\.js.*$");
// Find the file in the page
var fileSrc = $("script[src]").filter(function () {
return reg.test($(this).attr("src"));
}).first();
if (0 === fileSrc.length) {
console.log("Could not get location of " + fileName + ".js");
} else {
// Return the path without parent folder
return fileSrc.attr("src").replace(regReplace, "/");
}
};
// Call the function with the referenced filename and folder
// (the function could be adjusted to remove the need for the
// folder name, by hardcoding it, but this is more flexible)
var filePath = getFilePath("test-file", "js");
console.log("filePath: : " + filePath);
});

Related

I don't want to list all subfolders in gdrive [duplicate]

I need to list all files and folders of google drive up to some level. The code below is listing all the files and their folders (until it exceeds its time limit) and logs them. How to I add some way to stop if it recursively went, let´s say, 3 levels of subfolders?
function listFolders(folder) {
folder = folder || DriveApp.getRootFolder();
var folderName = folder.getName();
var files = folder.getFiles();
while (files.hasNext()) {
var fileName = files.next().getName();
Logger.log(folderName + " :: " + fileName);
}
var subfolders = folder.getFolders();
while (subfolders.hasNext()) {
listFolders(subfolders.next());
}
}
How about this modification? I think that there are several answers for your situation. So please think of this as just one of them.
Modified script:
When you use this modified script, please run main().
function main() { // Added
const folder = // Please set here.
const n = 3; // Please set here. This sample sets 3 as your question.
listFolders(folder, n);
}
function listFolders(folder, n) { // Modified
folder = folder || DriveApp.getRootFolder();
var folderName = folder.getName();
var files = folder.getFiles();
while (files.hasNext()) {
var fileName = files.next().getName();
Logger.log(folderName + " :: " + fileName);
}
if (--n == 0) return; // Added
var subfolders = folder.getFolders();
while (subfolders.hasNext()) {
listFolders(subfolders.next(), n); // Modified
}
}
Note:
Your script is Google Apps Script. So I modified your script as Google Apps Script.
Please modify it for your situation.
If I misunderstood your question, please tell me. I would like to modify it.

How to move a local image file to another folder using Node.js?

So I uploaded an image file and store it in a local folder, the assignment requirement is to move the image file from folder A to folder B, I have no clue to do this.
app.get('/fineupload003',function(req,res){
function moveApprovedFile(file, uuid, success, failure) {
var sourcePath = uploadedFilesPath;
var desPath = 'approved';
var desDir = desPath + "/";
var fileDes = desDir + file.name;
fs.access()
};
});
If the requirements is to just move the file and not copy it, you could rename the file which would act as moving.
fs.rename(sourcePath, desPath);
Read more on rename: https://nodejs.org/docs/latest/api/fs.html#fs_fs_rename_oldpath_newpath_callback

How to get FolderIterator containing only direct children of a folder in Google Drive

I am trying to create a script to print a list of full file paths for everything in my Google drive. The goal is to have a list like this:
./Docs/Doc1.gdoc
./Docs/Doc2.gdoc
./Docs/Doc3.gdoc
./Pics/2011/img1.jpg
./Pics/2011/img2.jpg
./Pics/2011/img3.jpg
...
It appears that this is not as simple as I thought, since Google Drive methods like getFolders() treat all folders as subfolders.
I tried writing something recursive to do this, until I realized the subfolders issue:
function getChildFolders(parent) {
var childFolders = parent.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
var pathString = childFolder.getName()
var files = childFolder.getFiles();
while (files.hasNext()) {
var fullPath = parent.getName()
var fileName = files.next().getName()
fullFilePath = pathString.concat('/', fileName)
Logger.log(fullFilePath);
}
// Recursive call
getChildFolders(childFolder);
}
}
I can't figure out a way to list the files in this manner in a hierarchical way. Has anyone been able to do this?
This should dump what you are looking for:
function dumpFilesInFolder(folder, path)
{
path = (path || "") + "/" + folder.getName();
Logger.log(path);
var subFolders = folder.getFolders();
while(subFolders.hasNext())
{
dumpFilesInFolder(subFolders.next(), path);
}
var files = folder.getFiles();
while(files.hasNext())
{
Logger.log(path + "/" + files.next().getName());
}
}
function startIt()
{
dumpFilesInFolder(DriveApp.getRootFolder());
}

How to use searchFile and searchFolder at the same time correctly? - App Script

The next script what it does is to search all the spreadsheets with a certain name in the drive starting from a certain folder.
function searchSSH(folder, path) {
if (folder == null && path == null) {
return
searchSSH(DriveApp.getFolderById("ID"), "");
}
var files = [];
path = path + "/" + folder.getName();
var searchFile = "fullText contains 'Project <>' and mimeType='" + MimeType.GOOGLE_SHEETS + "'";
var fileIterate = folder.searchFiles(searchFile);
while ( fileIterate.hasNext() ) {
var file = fileIterate.next();
var fileId = file.getId();
var name = file.getName();
files.push(name);
for (var i=0; i<files.length; i++){
Logger.log(files[i]);
}
}
var folderIterate = folder.getFolders();
while(folderIterate.hasNext()) {
var searchFold = searchSSH(folderIterate.next(), path);
for (var i = 0; i < searchFold.length; i++) {
files.push(searchFold[i]);
}
}
return files;
}
What I am trying to do is to see how I can do it so that I can also look for a certain folder just like the searchFile does and I try to do it like this...
function searchSSH() {
var Folder = DriveApp.getFolderById("ID");
var folders = Folder.searchFolders('fullText contains "project"');
while (folders.hasNext()) {
var folder1 = folders.next();
Logger.log(folder1.getName());
for (var i = 0; i < folder1.length; i++) {
files.push(folder1[i]);
}
}
var files = [];
var searchFile = "fullText contains 'test <>' and mimeType='" + MimeType.GOOGLE_SHEETS + "'";
var fileIterate = Folder.searchFiles(searchFile);
while ( fileIterate.hasNext() ) {
var file = fileIterate.next();
var fileId = file.getId();
var name = file.getName();
files.push(name);
for (var i=0; i<files.length; i++){
Logger.log(files[i]);
}
}
return files;
}
But doesn´t works. What I'm trying to do is to iterate through all the folders until I find the folder with the name project and keep iterating in that folder until I find all the spreadsheets with the test name but only search in the first folder.
I try to iterate between folders until I find the folder with the name Project and inside that folder keep iterating until I find the file with the name Test and that it is type spreadsheet.
The first script if it finds the file but I want to specify I look inside the folders with the name Project to improve the performance of the script
The second script I'm trying is not iterating, so it does not work because when I run it, it only finds the first folder and dont searching inside the others folders, Thanks for trying to help me. I hope that now it has given me to understand
From your this reply, I could understand as follows.
You want to retrieve Spreadsheet with the filename of Test under the folder with the name of Project. You want to do this with low process cost.
If my understanding is correct, how about these sample scripts? Please choose from them for your situation. I think that there are several answers for your situation. So please think of this answer as one of them.
Pattern 1:
Flow:
Retrieve files from filename of Test using getFilesByName().
Retrieve parent folders of each file using getParents().
If the folder name is Project and the mimeType is Spreadsheet, it retrieves the file.
Sample script:
var fileName = "Test";
var folderName = "Project";
var files = DriveApp.getFilesByName(fileName);
while (files.hasNext()) {
var file = files.next();
var parents = file.getParents();
while (parents.hasNext()) {
var parent = parents.next();
if (file.getMimeType() == MimeType.GOOGLE_SHEETS && parent.getName() == folderName) {
// do something
}
}
}
Pattern 2:
Flow:
Retrieve folders from folder name of Project using getFoldersByName().
Retrieve files in each folders using getFilesByName().
If the filename is Test and the mimeType is Spreadsheet, it retrieves the file.
Sample script:
var fileName = "Test";
var folderName = "Project";
var folders = DriveApp.getFoldersByName(folderName);
while (folders.hasNext()) {
var folder = folders.next();
var files = folder.getFilesByName(fileName);
while (files.hasNext()) {
var file = files.next();
if (file.getMimeType() == MimeType.GOOGLE_SHEETS && file.getName() == fileName) {
// do something
}
}
}
Pattern 3:
Flow:
Retrieve folder IDs of folder name of Project using getFoldersByName().
Retrieve files with the parent folder of Project and the filename of Test and the mimeType of Spreadsheet using searchFiles().
Sample script:
var fileName = "Test";
var folderName = "Project";
var folders = DriveApp.getFoldersByName(folderName);
var folderIds = [];
while (folders.hasNext()) {
folderIds.push(folders.next().getId());
}
folderIds.forEach(function(id) {
var params = "'" + id + "' in parents and title='" + fileName + "' and mimeType='" + MimeType.GOOGLE_SHEETS + "'";
var files = DriveApp.searchFiles(params);
while (files.hasNext()) {
var file = files.next();
// do something
}
});
References:
getFilesByName()
getFoldersByName()
getParents()
searchFiles()
If these were not what you want, I'm sorry.

node.js changes made in files not reflecting until the second run

I am converting all .png files to .jpg files in a directory and then running some manipulations on them which can be only to to jpeg files. But node.js doesn't seem to notice the converted files and the deleted png files until I run the same script again.
const fs = require('fs')
const pngToJpeg = require('png-to-jpeg');
let dirrCont = fs.readdirSync( dir );
files = dirrCont.filter( ( elm ) => /.*\.(png|jpg)/gi.test(elm) );
for (i in files)
{
let file = files[i]
let file_name_without_ext = file.replace(/\.[^/.]+$/, "")
let extension = file.match(/\.[^/.]+$/)
if (extension[0] == '.png')
{
console.log('found')
let buffer = fs.readFileSync(dir+file);
pngToJpeg({quality: 100})(buffer)
.then(output => fs.writeFileSync(dir+file_name_without_ext+'.jpg', output));
fs.unlinkSync(dir+file)
extension = '.jpg'
}
let target_file = target + file_name_without_ext + '.' + suffix + extension
// do some manipulations on dir+file_name_without_ext+extension
I always receive the error that the new jpg files are not found thus the manipulations don't work although the png files get converted to jpg files. When I run the same script again since now all the files are jpeg the file manipulations run this time.
EDIT
as suggested in one of the answers by #CertainPerformance
I changed the code to do most of my stuff inside the then block but again hit the same error
for (i in files)
{
let file = files[i]
let file_name_without_ext = file.replace(/\.[^/.]+$/, "")
let extension = file.match(/\.[^/.]+$/)
if (extension[0] == '.png')
{
console.log('found')
let buffer = fs.readFileSync(dir+file);
pngToJpeg({quality: 100})(buffer)
.then(output => {
fs.writeFileSync(dir+file_name_without_ext+'.jpg', output);
extension = '.jpg'
//
let target_file = target + file_name_without_ext + '.' + suffix + extension
// Do some manipulations
// I am done with the manipulations and I now want to delete
// the jpg file I just created
fs.unlinkSync(dir+file_name_without_ext+'.jpg') // Gives me back the same error
});
}
NOTE: There is a little bit of change up in the edit and I am deleting the jpg file instead of the png file (which I was doing originally)
As you can see by the .then, pngToJpeg is asynchronous - if you want to do work on dir+file_name_without_ext, you have to wait for the initial .then and the writeFileSync to resolve first. Put everything that depends on the asynchronous operations inside the then. For example:
if (extension[0] == '.png') {
console.log('found');
const buffer = fs.readFileSync(dir + file);
pngToJpeg({ quality: 100 })(buffer)
.then(output => {
fs.unlinkSync(dir + file);
fs.writeFileSync(dir + file_name_without_ext + '.jpg', output);
extension = '.jpg';
const target_file = target + file_name_without_ext + '.' + suffix + extension;
// do some manipulations on dir+file_name_without_ext+extension
});
}
(You should also take care not to implicitly create global variables. For example, use for (const i in files) instead, or perhaps for (const file of files) to avoid having to fiddle with the unimportant indicies)

Categories

Resources