Does anyone know an easy way to change a file extension in Javascript?
For example, I have a variable with "first.docx" but I need to change it to "first.html".
This will change the string containing the file name;
let file = "first.docx";
file = file.substr(0, file.lastIndexOf(".")) + ".htm";
For situations where there may not be an extension:
let pos = file.lastIndexOf(".");
file = file.substr(0, pos < 0 ? file.length : pos) + ".htm";
In Node.js:
path.join(path.dirname(file), path.basename(file, path.extname(file)) + '.md')
or more readably:
// extension should include the dot, for example '.html'
function changeExtension(file, extension) {
const basename = path.basename(file, path.extname(file))
return path.join(path.dirname(file), basename + extension)
}
Unlike the accepted answer, this works for edge cases such as if the file doesn't have an extension and one of the parent directories has a dot in their name.
I'd use this:
path.format({ ...path.parse('/path/to/file.txt'), base: '', ext: '.md' })
to change "/path/to/file.txt" to "/path/to/file.md".
file = file.replace(/\.[^.]+$/, '.html');
This probably won't get many upvotes but I couldn't resist.
This code will deal with the edge case where a file might not have an extension already (in which case it will add it). It uses the "tilde trick"
function changeExt (fileName, newExt) {
var _tmp
return fileName.substr(0, ~(_tmp = fileName.lastIndexOf('.')) ? _tmp : fileName.length) + '.' + newExt
}
EDITED: thanks #kylemit for a much better gist which uses the same logic, but in a much much neater way:
function changeExt(fileName, newExt) {
var pos = fileName.includes(".") ? fileName.lastIndexOf(".") : fileName.length
var fileRoot = fileName.substr(0, pos)
var output = `${fileRoot}.${newExt}`
return output
}
console.log(changeExt("img.jpeg", "jpg")) // img.jpg
console.log(changeExt("img.name.jpeg", "jpg")) // img.name.jpg
console.log(changeExt("host", "csv")) // host.csv
console.log(changeExt(".graphqlrc", "graphqlconfig")) // .graphqlconfig
path.parse("first.docx").name + ".html"
var file = "first.docx";
file = file.split(".");
file = file[0]+".html";
Related
Right now when file already exist I added prefix which is a timestamp to the filename to make it unique.
But instead of using timestamp I want to use ordinal suffix or add a number to the filename.
I would add an incremented number to the filename if the file exists. But can't quite wrap my head around how to do this in a good way.
Using timestamp works but its too long like when we display the filename it would be like for example so instead of using timestamp I just want to increment a number to a filename.
Hellworldfilename - 1593024232 - timestamp is too long , not a good idea.
It should based from existing records in the database . If for example I add a file with filename Hellworldfilename and it already existed then the new filename would be Hellworldfilename-1 , and if I add Hellworldfilename again the new filename would be Hellworldfilename-2 and so on and so forth. Any idea how we can make a filename everytime unique ?
Let me give an example. let us say I have 3 files in the database with filesname
DOC
DOC-1
DOC-2
If I add a file with filename DOC the new filename would be now DOC-3.
#Code for checking if file exists
const file = await context.service.Model.findOne({
where: { humanId: record.id, filename: data.filename },
paranoid: false,
});
if (file) {
const prefix = Date.now().toString();
// eslint-disable-next-line no-undef
const fileParts = data.filename.split('.');
filename = `${fileParts[0]}-${prefix}.${fileParts[1]}`;
You will need to check whether the filename ends with -somenumber. If so, then you can extract that number and increment it. Otherwise put 1 into the result:
function getNumberedFileName(fileN) {
//These are value initializations to cope with the situation when the file does not have a .
var fileName = fileN;
var fileExtension = "";
var lastDotIndex = fileN.lastIndexOf(".");
if ((lastDotIndex > 0) && (lastDotIndex < fileN.length - 1)) { //We are not interested in file extensions for files without an extension hidden in UNIX systems, like .gitignore and we are not interested in file extensions if the file ends with a dot
fileName = fileN.substring(0, lastDotIndex);
fileExtension = "." + fileN.substring(lastDotIndex + 1);
}
var lastDashIndex = fileName.lastIndexOf("-");
if ((lastDashIndex > 0) && (lastDashIndex < fileName.length - 1)) {
var lastPart = fileName.substring(lastDashIndex + 1);
if (!isNaN(lastPart)) {
var index = parseInt(lastPart) + 1;
return fileName.substring(0, lastDashIndex) + "-" + index + fileExtension;
}
}
return fileName + "-1" + fileExtension;
}
You could declare an object filenames in the global scope like
const filenames={};
and use it for keeping track of already opened files.
Below I defined a function makeUnique() hilighting the ideas I mentioned here before. It turns out I had to tweak my code a little bit but here is a working snippet:
const makeUnique=(function(){
const filenames={};
return function(fn){
const fileParts=fn.split(".");
const prefix=filenames[fn]!=null
? ++filenames[fn]
: filenames[fn]=0;
if (prefix) fileParts[Math.max(fileParts.length-2,0)]+='-'+prefix;
return fileParts.join('.')
}
})();
console.log(["abc","d.e.f.c","abc","ghi","abc","abc.txt","def",
"abc.txt","d.e.f.c","abc.txt","abc"].map(makeUnique))
.as-console-wrapper {max-height:100% !important}
I used an IIFE to generate a protected scope for the static object filenames. This is now accessible by all calls of makeUnique() but otherwise "private", i. e. cannot be modified accidentally from anywhere else.
I am writing a simple script on javascript for Alfresco Community. I have the script runnign everytime a new file is uploaded.
I need to check wether an specific filename (label.txt) exists in the folder. If it exists, I will use the information contained in the file for later treatment.
If I set the filename alone it works as long as the folder itself is the one with the script asigned, it works perfecly.
var labelFile = space.childByNamePath("label.txt");
if (labelFile != null)
{
...
}
When i set the inheritance of the script to lower level folders the script runs but still tries to find the label.txt file in the root folder. I am trying to locate the actual path of the uploaded document:
var dpath = document.displayPath + "/label.txt";
var labelFile = space.childByNamePath(dpath);
logFile.content += "labelFile: " + labelFile.displayPath + "\r\n";
if (labelFile != null)
{
...
}
I am getting a supposedly correct path in the dpath var, but I get a NULL result on the file object so I cannot read the file and its content.
What I am doing wrong?
What is "space" there? Try using "companyhome", see this for further ideas. http://docs.alfresco.com/4.0/references/API-JS-rootscoped.html
The current space ScriptNode (if any). For a script executing from a
rule, the space object is the space in which the rule resides. If the rule is inherited, this may not be the expected space.
The problem was not about inheritance, but space.childByNamePath just accepting relative paths, not absolute, so I ahd to calculate it from the space root:
var dpath = document.displayPath;
var dpatharray = dpath.split("/");
var dpathlength = dpatharray.length;
var spath = space.displayPath;
var spatharray = spath.split("/");
var spathlength = spatharray.length;
var labelpath = "";
for (var i=spathlength + 1; i<dpathlength; i++)
{
labelpath += dpatharray[i] + "/";
}
var labelFile = space.childByNamePath(labelpath + "label.txt");
I am using jade.compileClient to convert jade files to JS functions and I am having an issue when using escaped html.
When in jade I write:
h2= conditional ? 'String1 ' + moreText : otherCondition ? 'String2' : 'String3'
It is converted to:
function template(locals) {
var buf = [];
var jade_mixins = {};
var jade_interp;
buf.push("<h2>" + (jade.escape(null == (jade_interp = conditional ? 'String1 ' + moreText : otherCondition ? 'String2' : 'String3') ? "" : jade_interp)) + "</h2>");
// [more code, beside the point]
Seems great! The only problem is that the jade object doesnt exists (at least in my code), and, as you see, the converted functions calls to jade.escape (and some other functions like jade.attr, in other cases).
How can I make it work? Is something that I have to include that I am missing?
Thanks in advance.
Solved using jade/runtime:
var jade = require('jade/runtime');
var html = fs.readFileSync(filename);
var fn = jade.compileClient(html, { filename: filename });
fn(locals);
You can also download it from this link.
I have an input of type file, my question is: after I select the file, can the file name be limited to a certain number of characters ?
You can get the file name using
var filename = document.getElementById('file-id').value;
filename = filename.replace(/^.*[\\\/]/, '');
But limitation in sense, after uploading the file you can get the file name using above approach.
Then you can have
if (filename.length < 100 ) {
//do something
}
FYI: Evert thing happens only after the file being uploaded in client side. There is no use in limiting the filepath before uploaded to server.
Do you mean like this?
var limit = 8;
var fileName = document.getElementById("file-name-field").value();
// get both parts
var fileNameExtension = "." + fileName.split(".").pop();
var fileNameBase = fileName.substring(0, fileName.length()-fileNameExtension.length());
if(fileNameBase.length()>limit){
// now limit it and set it as fileName
fileName = fileNameBase.substring(0, limit) + fileNameExtension;
}
Most browsers don't allow modification of the value attribute of file fields. It's a security hole, because it would allow a malicious page to retrieve an arbitrary file using a hidden field.
Please try following JavaScript to check length of the file name.
function valueCheck()
{
var filePath = document.getElementById("file").value;
var fileName = filePath.replace(/[^\\\/]+$/, "");
if(fileName !=null && fileName.length >10)
{
alert('Filename if bigger');
}
}
Demo URL : http://jsfiddle.net/BhaveshKachhadiya/6EPvg/6/
Im new to using JS with photoshop and have some trouble. What I want to do is to get rid of the word "Online" in the file name of the current document and then save a JPG with new file name in a different folder.
With the help of the adobe reference I came up with the following script:
//Path where the final jpg should be saved
var JPGquality = 12;
var docPath="C:\Users\user\Desktop\test";
var docName='';
docName = activeDocument.name;
//Set new file name by replacing "_Online_" with "_"
var NewName = docName.replace("_Online_", "_");
var saveFile = new File(docPath+'/'+NewName+ '.jpg');
//Save JPG
function SaveJPEG(saveFile, jpegQuality) {
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpgSaveOptions.matte = MatteType.NONE;
jpgSaveOptions.quality = jpegQuality; //1-12
activeDocument.saveAs(saveFile, jpgSaveOptions, true,Extension.LOWERCASE);
}
The Script runs through but therewithout errors but nothing happens. It would be very helpful if someone could tell me what Ive done wrong. Hope someone helps me figuring out how to fix this ;)
I use this:
function saveAsJPG() {
jpgFile = new File(outputFolder + "/" + _CardFileName + ".jpg");
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpgSaveOptions.matte = MatteType.NONE;
jpgSaveOptions.quality = 12;
docRef.saveAs(jpgFile, jpgSaveOptions, true, Extension.LOWERCASE);
}
Try to use forward slashes in your docPath:
var docPath="C:/Users/user/Desktop/test";
\t (tab) and \u (beginning of a Unicode sequence) have special meanings in JS strings.
Or you can escape them, of course:
var docPath="C:\\Users\\user\\Desktop\\test";
The best way to write paths in javascript for photoshop automation is '/c/users/user/' That works on both mac and windows and you don't need to escape the backslashes