Nodejs get file extension - node.js

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

Related

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

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

cannot create /dev/stdout: No such device or address

I'm want to run a shell command via node and capture the result of stdout. My script works fine on OSX, but not on Ubuntu.
I've simplified the problem and script to the following node script:
var execSync = require('child_process').execSync,
result = execSync('echo "hello world" >> /dev/stdout');
// Do something with result
Results in:
/bin/sh: 1: cannot create /dev/stdout: No such device or address
I have tried replacing /dev/stdout with /dev/fd/1
I have tried changing the shell to bash... execSync('echo ...', {shell : '/bin/bash'})
Like I said, the problem above is simplified. The real script accepts as a parameter the name of a file where results should be written, so I need to resolve this by providing access to the stdout stream as a file descriptor, i.e. /dev/stdout.
How can I execute a command via node, while giving the command access to its own stdout stream?
On /dev/stdout
I don't have access to an OSX box, but from this issue on phantomjs, it seems that while on both OSX/BSD and Linux /dev/stdout is a symlink, nonetheless it seems to work differently between them. One of the commenters said it's standard on OSX to use /dev/stdout but not for Linux. In another random place I read statements that imply /dev/stdout is pretty much an OSX thing. There might be a clue in this answer as to why it doesn't work on Linux (seems to implicitly close the file descriptor when used this way).
Further related questions:
https://unix.stackexchange.com/questions/36403/portability-of-dev-stdout
bash redirect to /dev/stdout: Not a directory
The solution
I tried your code on Arch and it indeed gives me the same error, as do the variations mentioned - so this is not related to Ubuntu.
I found a blog post that describes how you can pass a file descriptor to execSync. Putting that together with what I got from here and here, I wrote this modified version of your code:
var fs = require('fs');
var path = require('path');
var fdout = fs.openSync(path.join(process.cwd(), 'stdout.txt'), 'a');
var fderr = fs.openSync(path.join(process.cwd(), 'stderr.txt'), 'a');
var execSync = require('child_process').execSync,
result = execSync('echo "hello world"', {stdio: [0,fdout,fderr] });
Unless I misunderstood your question, you want to be able to change where the output of the command in execSync goes. With this you can, using a file descriptor. You can still pass 1 and 2 if you want the called program to output to stdout and stderr as inherited by its parent, which you've already mentioned in the comments.
For future reference, this worked on Arch with kernel version 4.10.9-1-ARCH, on bash 4.4.12 and node v7.7.3.

add a permitted path to ghostscipt running configuration

I use a program which create me postscript file before using ps2pdf to make it a readable pdf, i've made a program which add some string to overwrite the company new logo. (The first program can't import image file itself).
I add the string before the before-last line of the file (" showpage").
While running my program to add the logo there is no error.
With the option -dNOSAFER everything is fine, but by default it's set to -dSAFER, and an invalidfileaccess error pop, the files are 6 jpg images alone in their directory.
I don't want to make it run with the -dNOSAFER option on. As it will fully open the file system.
In the documentation I've seen that there is a "permitted path" setting, but i can't find nowhere to set this up. Is it just a command line option to set in the command launching the program ? Or is there a config file for GhostScript / ps2pdf where i can put the path to this directory as permitted path.
in this documentation :
http://www.ghostscript.com/doc/current/Use.htm
I only find
-dTTYPAUSE
Causes Ghostscript to read a character from /dev/tty, rather than
standard input, at the end of each page. This may be useful if input
is coming from a pipe. Note that -dTTYPAUSE overrides -dNOPAUSE. Also
note that -dTTYPAUSE requires opening the terminal device directly,
and may cause problems in combination with -dSAFER. Permission errors
can be avoided by adding the device to the permitted reading list
before invoking safer mode
gs -dTTYPAUSE -dDELAYSAFER -c '<< /PermitFileReading [ (/dev/tty)] >> setuserparams .locksafe' -dSAFER
The quote is just for the context but is this a way to put the permitted path ?
As gs automatically launch with the full system as readOnly there will be no difference ? There is no other find result for PermitFile in this page.
Try adding the required path to the search path with -I (Include) See Use.htm, section 8 How Ghostscript finds files. This should only be a problem if you are using 'run' or similar to read files from another location.
The section on TTYPAUSE is not relevant.

"Unable to open image" error when using ImageMagick's Filename References

I'm using ImageMagick to do some image processing from the commandline, and would like to operate on a list of files as specified in foo.txt. From the instructions here: http://www.imagemagick.org/script/command-line-processing.php I see that I can use Filename References from a file prefixed with #. When I run something like:
montage #foo.txt output.jpg
everything works as expected, as long as foo.txt is in the current directory. However, when I try to access bar.txt in a different directory by running:
montage /some_directory/#bar.txt
output2.jpg
I get:
montage: unable to open image
/some_directory/#bar.txt: No such file
or directory # blob.c/OpenBlob/2480.
I believe the issue is my syntax, but I'm not sure what to change it to. Any help would be appreciated.
Quite an old entry but it seems relatively obvious that you need to put the # before the full path:
montage #/some_directory/bar.txt output2.jpg
As of ImageMagick 6.5.4-7 2014-02-10, paths are not supported with # syntax. The # file must be in the current directory and identified by name only.
I haven't tried directing IM to pull the list of files from a file, but I do specify multiple files on the command line like this:
gm -sOutputFile=dest.ext -f file1.ppm file2.ppm file3.ppm
Can you pull the contents of that file into a variable, and then let the shell expand that variable?

Function works properly with relative path input but NOT with absolute path input

There exists a function that is part of a software package (MRICro), and it is called 'dcm2nii.'
When a relative path is used as the output directory, the function works perfectly well.
But, when the absolute path to the exact same folder is used, the function breaks down.
Example (absolute path):
dcm2nii -o /net/user1/project_name/Data/2011_01_10_SVD1/Processed/3_fMRI_rest E2538S3I00*
Example (relative path):
dcm2nii -o ../Processed/3_fMRI_rest E2538S3I00*
Sample error message that occurs when using the absolute path for the output folder (the last line suggests that the output file can not be created):
Validating 52 potential DICOM images.
Found 52 DICOM images.
Converting 52/52 2
E2538S3I0001.MR.dcm->20110110_112950E2538S3I0001MRFPSD1F29OCT2010RCs003a1001.nii
GZip 20110110_112950E2538S3I0001MRFPSD1F29OCT2010RCs003a1001.nii
unable to create /net/user1/project_name/Data/2011_01_10_SVD1/Processed/3_fMRI_rest/20110110_112950E2538S3I0001MRFPSD1F29OCT2010RCs003a1001.nii.gz
I do not know if this problem is due to me doing something wrong in Linux/bash or due to the function actually having a mistake.
But, any input is appreciated.
On a more general level, I am looking for any foreseeable reason for why a function would be able to use a relative folder path and not an absolute one (provided that they resolve to the same location).
EDIT: pwd gives:
/net/user1/project_name/Data/2011_01_10_SVD1/3_fMRI_rest
you would really have to show us the code before we can tell you what the cause of the problem is, however the behaviour you described is possible
This is an example of poor practice but consider the following
#!/bin/bash
....
current_dir = $(pwd)
out_dir = $1
cd ${somewhere}
..... do stuff
#no we want to come back to create the output dir
mkdir ${current_dir}/$out_dir
This appears to be a bug of some kind.. I am experiencing the same issue. If I try to execute this command on data in my home folder, I get the same error.
However, if I move my data to a path that doesn't involve any expansion, i.e. ''/tmp/data'', the program executes fine.

Resources