NodeJS - Find a given file by name and ext regardless of location, from inside a working directory (Closed) - node.js

How do I search for a specific file by name and extension in a working directory, regardless of the file's path from inside that working directory?
For example, if we are searching for foo.txt inside our first working directory, but it's located within a file path like the example below
workDir/folder2/is/foo/directory/foo.txt
Then say for further example, we want to then search for foo.txt inside our second working directory, but the file is located within a different file path like below
workDir/folder11/this/way/to/foo.txt
How would I find foo.txt regardless of the file's path, inside a working directory?
I am Using the below JavaScript code in my NodeJS project's controller.js file to try and achieve this.
NOTE: In real-time, every working directory this would be used on, would be named differently
controller.js
var fooPath = GetFooPath(data, path.join(workDir, "folder11/"));
if (fooPath == -1) {
console.log("Cannot find the foo file!");
return;
}

You could use globbing
glob("absolute/path/to/workDir/**/*.txt", options,
function (error, files) {
// files is an array of filenames.
// If the `nonull` option is set, and nothing
// was found, then files is ["**/*.js"]
// error is an error object or null.
})
NPM glob

Related

renaming all files in a folder deletes all files

I am trying to rename all files in a folder but the current method im using is deleting all the files in that folder. Why is that happening and how can I fix it? Thanks in advance.
fs.readdirSync(path.join(__dirname, '..', 'blah')).forEach(file => {
fs.rename(path.join(__dirname, '..', 'blah', file), file.replaceAll(' ', '~'), (err) => {
if (err) throw err;
console.log('Rename complete!');
});
});
On unix systems (macOS, linux) the ~ symbol has a special meaning in a file path, you can't use it for a file name.
So for example, ~/Music/blah.mp3 means /User/John/Music/blah.mp3. It's kind of like . or ... So you shouldn't use it for the name.
When renaming a file, you need to give the full absolute path to that file in the new name, not just the name of the file.
So renaming path.join(__dirname, 'blah.mp3') into 'foo.mp3' would move the file from /User/John/a/b/blah.mp3 (depending on where "__dirname" is) to /foo.mp3 (at the root of your system).
I think readdirSync returns an array of full paths, so you shouldn't need to prefix file with __dirname/../blah
Is it possible you're trying to rename "files that don't exist" (see point #3) into files that already exists (maybe your filename doesn't contain ' ' or maybe '~' gets ignored because of point #1). And when renaming, the docs do mention:
In the case that newPath already exists, it will be overwritten.
(https://nodejs.org/api/fs.html#fsrenameoldpath-newpath-callback)

pathlib mkdir creates a folder by filename

I have the following preexisting folder in my machine
D:\scripts\myfolder
I want my script to create a folder named logs and create a file log.txt in it. So the path would look like
D:\scripts\myfolder\logs\somelog.txt
So I used
p = pathlib.Path("D:\scripts\myfolder\logs\somelog.txt")
p.mkdir(parents=True, exisit_ok=True)
Now
print(p.parents[0]) ==> D:\scripts\myfolder\logs
print(p.parents[1]) ==> D:\scripts\myfolder
print(p.parents[2]) ==> D:\scripts
So, as per Path.mkdir documentation
p.mkdir(parents=True, exisit_ok=True) should create the folders logs, myfolder or scripts and so on if they don't exist.
But it creates a folder by the name some.txt inside logs folder, although it is none of the parents. Why is that so?
I understand that the workaround is to use pathlib.Path("D:\scripts\myfolder\logs")
The entire point of mkdir is to create the directory pointed to by its argument. Passing in parents=True creates the parent folders in addition.
Create a new directory at this given path. [...] If parents is true, any missing parents of this path are created as needed; [1]
If you want to ensure the containing directory exists, create the parent of your path:
p = pathlib.Path("D:\scripts\myfolder\logs\somelog.txt")
p.parent.mkdir(parents=True, exist_ok=True)
That's the way Pathlib.mkdir works. It can't tell if the final component should be a file or a directory. parents=True means to create also parents, not only parents. If the final path component is always a file, you could avoid it like
p.parents[0].mkdir(parents=True)

Nodejs get file extension

I have a folder with images and they can have different formats but the name will always be unique. Is there a way to get the file extension if I know the file's name without the extension (eg. index and not index.html)? I could just check if the file exists for every extension I expect to be there but that seems like a bad solution to me.
Example:
I know there is an image called PIC but I don't know the extension (could be either '.png', '.jpg' etc.) therefore I can not use the file command.
Well, if your running Unix based systems, this could be a workaround.
var sys = require('util')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) {
console.log(stdout)
}
// this is where you should get your path/filename
var filename = "login";
// execute unix command 'file'
exec("file " + filename, puts);
I tested it for a PNG file and an EJS file, both with no extensions (what wouldn't make difference).
The results are below:
PNG:
photo: PNG image data, 100 x 100, 8-bit/color RGB, non-interlaced
EJS (what's basically a HTML):
login: HTML document, ASCII text
You can check file command line parameters to make it easier to work with the string (e.g. file -b filename).
If using Windows, then you'd have to check an alternative command for file.
Hope it's somehow useful.
I know I'm late to the party, but you can use the grep command in unix based systems.
ie ls | grep PIC. What this does is first give a directory listing of the working directory, and then searches for the phrase PIC from the output of the directory listing and prints it. (so the only thing that will be printed is the filename)
In Windows, use dir PIC.* /b
You can execute these commands using child_process as shown in other answers
var path = require('path')
path.extname('index.html')
// returns
'.html'
Here is the referenced answer
Node.js get file extension
Updated :
https://www.npmjs.com/package/file-extension
npm install --save file-extension
allows you to specify a filename then it will return the extension

How to use file from folder in bash

I use this code to upload text file to the folder. It works fine, file is in folder. File is named by multimedia id -"mid.txt"(i.e: "1.txt"):
Part of upload.php:
if(isset($_POST['btn-upload']))
{
$folder="/var/www/tmp/textgrid_uploads/$mid.txt";
I want to use the uploaded file "$mid.txt" from "textgrid_uploads" directory in script for conversion. The script "conversion.sh" has defined "input", "output" and "temporary" file because it has to be defined to store temp file:
Part of script "conversion.sh":
mid=$1
infile="/var/www/tmp/textgrid_uploads/$mid"
outfile="/var/www/tmp/mlf/${mid}.mlf"
tmpfile="/var/www/tmp/mlf/${mid}.tmp"
The script works fine, becasuse I tested it for files which were created manually on server using: vim 1.txt. Problem is when I want to use script "conversion.sh" for file which was uploaded on server using "upload.php". After using script "conversion.sh" It creates blank file called "$mid.mlf" in "mlf" directory with no text. Running of "conversion.sh": i.e: ./conversion.sh 1.txt

Replacing files in one folder and all its subdirectories with modified versions in another folder

I have two folders, one called 'modified' and one called 'original'.
'modified' has no subdirectories and contains 4000 wav files each with unique names.
The 4000 files are copies of files from 'original' except this folder has many subdirectories inside which the original wav files are located.
I want to, for all the wav files in 'modified', replace their name-counterpart in 'original' wherever they may be.
For example, if one file is called 'sound1.wav' in modified, then I want to find 'sound1.wav' in some subdirectory of 'original' and replace the original there with the modified version.
I run Windows 8 so command prompt or cygwin would be best to work in.
As requested, I've written the python code that does the above. I use the 'os' and 'shutil' modules to first navigate over directories and second to overwrite files.
'C:/../modified' refers to the directory containing the files we have modified and want to use to overwrite the originals.
'C:/../originals' refers to the directory containing many sub-directories with files with the same names as in 'modified'.
The code works by listing every file in the modified directory, and for each file, we state the path for the file. Then, we look through all the sub-directories of the original directory, and where the modified and original files share the same name, we replace the original with the modified using shutil.copyfile().
Because we are working with Windows, it was necessary to change the direction of the slashes to '/'.
This is performed for every file in the modified directory.
If anyone ever has the same problem I hope this comes in handy!
import os
import shutil
for wav in os.listdir('C:/../modified'):
modified_file = 'C:/../modified/' + wav
for root, dirs, files in os.walk('C:/../original'):
for name in files:
if name == wav:
original_file = root + '/' + name
original_file = replace_file.replace('\\','/')
shutil.copyfile(modified_file, original_file)
print wav + ' overwritten'
print 'Complete'

Resources