Creating directory after each event - javascript

I am trying to create a directory after each button click event.
This works just until 10 directories
5612cfea107f9e0f356b3dee_1
5612cfea107f9e0f356b3dee_2
5612cfea107f9e0f356b3dee_3
5612cfea107f9e0f356b3dee_n
and then I am getting this error:
Error: EEXIST: file already exists, mkdir 'user/public/uploadGallery/5612cfea107f9e0f356b3dee_10'
app.post('/createDirectories', function(req, res) {
var id = '5612cfea107f9e0f356b3dee';
var pathDirectory = __dirname + '/public/uploadGallery/' + id;
fs.readdir(__dirname + '/public/uploadGallery/', function (err, files) {
var countVal = files.filter(junk.not).length;
var fileVal = files.filter(junk.not);
if(countVal == '0'){
fs.mkdirSync(pathDirectory + '_' + 1);
console.log("Directory created: " + pathDirectory + '_' + 1);
}else{
var lastElem = fileVal[fileVal.length-1];
var lastElemSplitValue = lastElem.split("_")[1];
var valInt = parseInt(lastElemSplitValue, 10) +1;
fs.mkdirSync(pathDirectory + '_' + valInt);
}
});
});
What can I do to fix this problem? I wanna create n directories.
Thanks for your help.
machu

The problem is sorting
you'll have directories
_1
_2
...
_9
add the 10th - and, in alphabetical or lexical order, you'll have
_1
_10
_2
...
_9
so, the last folder is _9 ... 9 + 1 = 10 ... that already exists!
You could change your code to
} else {
var valInt = Math.max.apply(null, fileVal.map(function(entry) {
return parseInt(entry.split("_").pop(), 10);
})) + 1;
fs.mkdirSync(pathDirectory + '_' + valInt);
}
This applies Math.max to the result of mapping the fileVal entries to the parseInt of the last part of each of the fileVal entries split by '_'

Related

ServiceNow - Change a file name in Midserver

I am currently trying to replace the name of a file in the Mid Server after a scheduled export.
The idea here is that the file goes with the name in the format "file_name_datetime" and the customer needs "datetime_file_name" for the file to be correctly read by another system.
My main idea was to rename the file after the export to the correct format, but if there is a way of changing the file name to the required one I could do that also.
I would love to hear from you guys as I have no idea how can I do this.
Thanks in advance.
If anyone is interested in the answer, see below:
Script include:
initialize: function() {
this.filePath = gs.getProperty('directory_path');
this.midServer = gs.getProperty('midserver');
this.authMidServerBase64 = gs.getProperty('authmidserver');
},
nameChange: function(exportSetName) {
var exportGr = new GlideRecord("sys_export_set_run");
exportGr.addEncodedQuery("set.nameSTARTSWITH" + exportSetName);
exportGr.orderByDesc("completed");
exportGr.query();
if (exportGr.next()) {
var attachSysID = exportGr.ecc_agent_attachment.sys_id;
}
var attachGr = new GlideRecord("sys_attachment");
attachGr.addEncodedQuery("table_sys_idSTARTSWITH" + attachSysID);
attachGr.query();
if (attachGr.next()) {
var attachName = attachGr.file_name;
var attachDate = attachName.match((/\d+/));
var newName = attachDate + '_' + exportSetName + '.csv';
}
var jspr = new JavascriptProbe(this.midServer);
jspr.setName('FileNameChange'); // This can be any name
jspr.setJavascript('var ddr = new MidServer_script_include(); res = ddr.execute();');
jspr.addParameter("verbose", "true");
jspr.addParameter("skip_sensor", "true"); // prevent Discovery sensors running for the ECC input
jspr.addParameter("filename", this.filePath + "\\" + attachName);
jspr.addParameter("filePath", this.filePath);
jspr.addParameter("newName", this.filePath + "\\" + newName);
jspr.addParameter("operation", "rename");
return jspr.create();
},
Mid Server Script include:
initialize: function() {
/**
*** Set up the Packages references
**/
this.File = Packages.java.io.File;
this.FileOutputStream = Packages.java.io.FileOutputStream;
this.FileInputStream = Packages.java.io.FileInputStream;
this.Path = Packages.java.nio.file.Path;
this.Paths = Packages.java.nio.file.Paths;
this.Files = Packages.java.nio.file.Files;
this.StandardCopyOption = Packages.java.nio.file.StandardCopyOption;
/**
/* Set up the parameters
**/
this.verbose = probe.getParameter("verbose");
this.filePath = probe.getParameter("filePath");
this.filename = probe.getParameter("filename");
this.operation = probe.getParameter("operation");
this.newName = probe.getParameter("newName");
result = "initialize complete";
},
execute: function() {
if (this.operation == 'rename') {
this.fileRename(this.filename, this.newName);
}
return result;
},
fileRename: function(fileName, newName) {
result+= "\r\n Renaming file.";
this._debug(result);
try {
var res = this._moveFile(fileName, newName);
} catch (e) {
result += "\r\n Erro no renomeamento do ficheiro: " + e;
this._debug(result);
}
},
_moveFile: function(initialPath, targetPath) {
try {
this._debug("Initiating file move function");
var inPath = this.Paths.get(initialPath);
var tgPath = this.Paths.get(targetPath);
var res = this.Files.move(inPath, tgPath, this.StandardCopyOption.REPLACE_EXISTING);
result += "File successfully moved from: " + initialPath + " to: " + targetPath + " \r\n Result: " + res;
this._debug(result);
} catch (e) {
this._debug('Error:' + e);
}
},
_debug: function(m) {
if (this.verbose == "true") {
ms.log("::: Mid Server script include logger ::: " + m);
}
},
https://community.servicenow.com/community?id=community_question&sys_id=a56b38a6db326490fa192183ca961987

Write javascript array elements to file

I am trying to have a node js script write some coordinates to a csv file for use in a Newman CLI script. I have the following:
const axios = require('axios');
var move_decimal = require('move-decimal-point');
var sLat = 45.029830;
var sLon = -93.400891;
var eLat = 45.069523;
var eLon = -94.286001;
var arrLatLon = []
axios.get('http://router.project-osrm.org/route/v1/driving/' + sLon + ',' + sLat + ';' + eLon + ',' + eLat + '?steps=true')
.then(function (response) {
for (let i = 0; i < response.data.routes[0].legs.length; i++) {
//console.log(response.data)
for (let ii = 0; ii < response.data.routes[0].legs[i].steps.length; ii++) {
//console.log('leg ' + i + " - step " + ii + ": " + response.data.routes[0].legs[i].steps[ii].maneuver.location[1] + "," + response.data.routes[0].legs[i].steps[ii].maneuver.location[0]);
// Declaring Latitude as 'n' & Longitude as 'nn' for decimal calculations
var n = response.data.routes[0].legs[i].steps[ii].maneuver.location[1]
var nn = response.data.routes[0].legs[i].steps[ii].maneuver.location[0]
// Latitude calculatiuons to make 'lat' values API friendly
var y = move_decimal(n, 6)
var p = Math.trunc(y);
// Longitude calculations to make 'lon' values API friendly
var yy = move_decimal(nn, 6)
var pp = Math.trunc(yy);
arrLatLon.push(p + "," + pp);
}
console.log(arrLatLon)
}
})
I have been looking through and trying numerous different tutorials/code snippets regarding writing the array elements from arrLatLon to an output file on my local machine, but none have been successful. The current code outputs the lat,lon correctly, console.log(arrLatLon) outputs:
[ '45029830,-93400894',
'44982812,-93400740',
'44977444,-93400530',
'44973116,-93410884',
'44971101,-93450400',
'45035514,-93766885',
'45035610,-93766886',
'45081631,-94286752',
'45070849,-94282026' ]
any help would be greatly appreciated. Thanks.
With nodejs you can easily write files using the fs module
const fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
in your case you can simply do something like
const fs = require('fs');
// I'm converting your array in a string on which every value is
// separated by a new line character
const output = arrLatLon.join("\n");
// write the output at /tmp/test
fs.writeFile("/tmp/test", output, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
Let me forward you to this question for more information Writing files in Node.js

how solve long name folders path creation with node js

this is not really a question because i will answer to it but maybe it will be usefull for someone else:
i'm on windows and ,
for testing purpose i add to create a high number of folders in folder,
then i use this code ,
createFolder.js:
var fs = require('fs')
var root = './root/'
var start = 0
var end = 10000
while (start < end)
{
fs.mkdirSync(root+start)
root +=start+'/'
}
this was a huge mistake .
because of this , i was unable to delete the root folder because of the long path name, this was really anoying.
so i try few different method, includely this one :
How to delete a long path in windows.
but i can't figure why it just did not work.
i really was embarassed.
but when i did some test , i figured out than i was able to rename the folder.
as i'm a linux user to i remenber than you can move folder with rename command.
then this was the solution, but you can't did it straight be cause it will be just to long.
so here a litlle snippet that will help you in this case
uid.js:
module.exports=function( ){
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
repair.js:
var fs = require('fs')
var uid = require('./uid.js')
var root= __dirname+'\\renamed\\'
var rootLength = root.split('\\')
console.log(root,rootLength.length)
var count = 0
var pathIt = function(path){
if(fs.existsSync(path) == true){
var dir = fs.readdirSync(path)
if(dir.length > 0)
{
for(d in dir ){
if(fs.existsSync(path+dir[d]) == true && fs.statSync(path+dir[d]).isDirectory() == true)
{
count++
console.log(count)
pathIt(path+dir[d]+'\\')
}else{
console.log("count %s",count)
console.log(path)
}
}
}else{
if(path != __dirname){
var way = path.split('\\')
console.log(way.length)
while(way.length != rootLength.length)
{
console.log(way.length)
var joinIt = way.join('\\')
if(fs.existsSync(joinIt) == true)
{fs.renameSync(joinIt,'./root/'+uid())}
way.pop()
}
console.log(way)
}
}
}
}
pathIt(root)
with this code you will simply walk through the last created folder and get the full unc.
then it will simply move all the folder from the last one until the first into another folder root, here you will be able to select them all using ctrl+a in the folder and simply delete it.
i hope this will be helpfull to anyone.

Looping over objects in array and adding property to each

I'm getting an array of files, and then I want to add the date and size properties to each of those file objects, but using the code below, they don't get added. I know that's my fs.statSync(p + file).mtime.getTime() and fs.statSync(p + file).size have values in them.
var files = fs.readdirSync(p);
files.sort(function(a, b) {
return fs.statSync(p + a).mtime.getTime() -
fs.statSync(p + b).mtime.getTime();
});
files.forEach(function(file) {
file.date = fs.statSync(p + file).mtime.getTime();
file.size = fs.statSync(p + file).size;
});
console.log('files::'+files); // doesn' have the new file.date and file.size property.
When you writing value into file variable it's not saving because file it's variable that lives into local scope. So a quick solution for this:
var files = fs.readdirSync(p),
result = [];
files.sort(function(a, b) {
return fs.statSync(p + a).mtime.getTime() -
fs.statSync(p + b).mtime.getTime();
});
files.forEach(function(file) {
file.date = fs.statSync(p + file).mtime.getTime();
file.size = fs.statSync(p + file).size;
result.push(file);
});
console.log('files::' + result);
Similar to Eugene's answer, but this uses map:
files = files.map(function(file) {
file.date = fs.statSync(p + file).mtime.getTime();
file.size = fs.statSync(p + file).size;
return file;
});
DEMO
The file variable is a local variable. Without having to create a new array as Eugene did, you can update the original array in this way:
var files = fs.readdirSync(p);
files.sort(function(a, b) {
return fs.statSync(p + a).mtime.getTime() -
fs.statSync(p + b).mtime.getTime();
});
files.forEach(function(file, index, array) {
array[index].date = fs.statSync(p + file).mtime.getTime();
array[index].size = fs.statSync(p + file).size;
});
console.log('files::'+files);

concatenating strings in .each loop

This may be a dumb question but I can't seem to get it or find it anywhere.
I have a .each function that returns the id's of a bunch of divs on a page and then assigns them a number. I need them to be outputted in a specific format all as one string so I can pass them to a database and use them as "sort_order" values. (I split them through a sproc in my database).
Here is my code:
jQuery('#updateAllContentButton').click(function() {
var count = 1;
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
var data_str = (id + ':' + count + '~');
console.log(data_str);
count++;
});
});
So that returns each data_str on a separate line but I need it to return it like this:
144:2~145:3~146:4~147:4~148:5 (so on)
Any help would be appreciated, thanks!
Use map and join :
jQuery('#updateAllContentButton').click(function() {
console.log(jQuery('.CommentaryItem').map(function(i) {
return GetID(jQuery(this)) + ':' + (i+1);
}).get().join('~'));
});
Note that you don't have to count yourself : Most jQuery iteration functions do it for you.
You can use an array for that. Like this...
jQuery('#updateAllContentButton').click(function() {
var count = 1;
var arr = [];
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
var data_str = (id + ':' + count + '~');
arr.push(data_str);
//console.log(data_str);
count++;
});
console.log(arr.join());
});
try this:
jQuery('#updateAllContentButton').click(function() {
var count = 1;
var data_str = "";
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
data_str += (id + ':' + count + '~');
console.log(data_str);
count++;
});
});
change
var data_str = (id + ':' + count + '~');
to
data_str+ = (id + ':' + count + '~');
full code
jQuery('#updateAllContentButton').click(function() {
var count = 1,
data_str;
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
data_str += (id + ':' + count + '~');
console.log(data_str);
count++;
});
});

Categories

Resources