how solve long name folders path creation with node js - javascript

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.

Related

ERROR Error: ENOENT: no such file or directory, open when create a text file in node js

I'm new to node js please help me to solve this.
I want to create a text file in node js. I'm using following code segment for that.
var d = new Date();
var filename = '../upload/' + d.getFullYear() + '-' + pad((d.getMonth() + 1).toString()) + '-' + pad((d.getDate()).toString()) + '.txt';
if (currentlogstreamfilename != filename) {
currentlogstreamfilename = filename;
console.log("Path: " + currentlogstreamfilename);
currentlogstream = fs.createWriteStream(currentlogstreamfilename, { flags: 'a' });
}
locally this is working perfectly. But inside the docker I'm getting.
ERROR Error: ENOENT: no such file or directory, open '../upload/2018-11-07.txt'
Any solution for this..
Thanks for all. I used node path as following. It worked fine.
var path = require('path');
var filename = path.join(__dirname,'../upload/' + d.getFullYear() + '-' + pad((d.getMonth() + 1).toString()) + '-' + pad((d.getDate()).toString()) + '.txt');
don't use relative path name such ../. use an absolute path in your application. you can say
filename = __dirname + '/upload + d.getYear() + ...
or if you want to save this file in the parent directory you should first get running process root path. which you can say:
filename = process.cwd() + 'uploads/' + d.getYear() + ...

Creating directory after each event

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 '_'

my javascript for creating unique IDs isn't working

I'm trying to create unique ids, and I can't see why it's not working. Guess I'm blind staring at the same code for too long. I would appreciate if someone could help me! :)
function laggtill(cool, namnVara) {
var date = new Date();
var id = "" + date.getHours() + date.getMinutes() + date.getSeconds() + date.getMilliseconds();
var vara = document.createElement("li");
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
var span = document.createElement("span");
span.innerText = namnVara;
vara.appendChild(checkBox);
vara.appendChild(span);
cool.appendChild(vara);
}
var button = document.getElementById("knapp");
button.onclick = function() {
var skriva = document.getElementById("skriva")
var namnVara = skriva.value;
if (!namnVara || namnVara == "" || namnVara == " ") {
return false;
}
};
Stole this from jQuery UI. It's as simple as it's effective:
// at initialization
var uuid = 0;
// and when you need a unique id
var uniqueId = 'uid-' + (++uuid);
No need for complicated stuff like getting dates etc. unique != complicated
And to set the ID to an element:
var element = document.createElement('div');
element.id = uniqueId;
And if you want to use it more often in a script, you could create a function:
var uuid = 0; // put it in the 'global scope'
var uniqueId = function() {
return 'uid-' + (++uuid);
};
alert(uniqueId()); // uid-1
alert(uniqueId()); // uid-2
if you really want to keep the date.
var d = new Date();
var id = "" + d.getHours() + d.getMinutes() + d.getSeconds()+ d.getMilliseconds();
add some stuff to generate guid to :
var guid = (function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
})();
http://jsfiddle.net/mz4qpg1L/1/
if you want to append id to youre control, i like appending html directly :
vara.appendChild('<span id=' + id + ' ></span>');
this way you can put any attribute you want.

Javascript string to Guid

in javascript, what is the easiest way to convert this string
798205486e954fa880a0b366e6725f71
to GUID format like this
79820548-6e95-4fa8-80a0-b366e6725f71
this is the messy way I do it :) im looking for the cleanest way
var employeeId = shift.employee.id.substring(0, 8) + "-" + shift.employee.id.substring(8, 12)
+ "-" + shift.employee.id.substring(12, 16) + "-" + shift.employee.id.substring(16, 20) + "-" + shift.employee.id.substring(20, 32);
Cleanest way?
Shortest:
var txt = shift.employee.id;
txt.replace(/([0-z]{8})([0-z]{4})([0-z]{4})([0-z]{4})([0-z]{12})/,"$1-$2-$3-$4-$5");
//"79820548-6e95-4fa8-80a0-b366e6725f71"
or if you don't care about the acceptable characters, it can be be even shorter (and cleaner):
txt.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5"); //boom!
Some don't like using regex for everything, but I liked it.
I did it in string manipulation
var str = "798205486e954fa880a0b366e6725f71";
var parts = [];
parts.push(str.slice(0,8));
parts.push(str.slice(8,12));
parts.push(str.slice(12,16));
parts.push(str.slice(16,20));
parts.push(str.slice(20,32));
var GUID = parts.join('-');
console.log(GUID) // prints expected GUID
I did it this way because I don't like inserting characters between strings. If there is any problem tell me.
Or you could use a for loop like bellow
var str = "798205486e954fa880a0b366e6725f71";
var lengths = [8,4,4,4,12];
var parts = [];
var range = 0;
for (var i = 0; i < lengths.length; i++) {
parts.push(str.slice(range,range+lengths[i]));
range += lengths[i];
};
var GUID = parts.join('-');
console.log(GUID);
You could use an regular expression:
var rxGetGuidGroups = /(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})/,
employeeId = shift.employee.id.replace(rxGetGuidGroups, '$1-$2-$3-$4-$5');
jsFiddle
Try this function, It will return string in GUID format
function getGuid(str){
return str.slice(0,8)+"-"+str.slice(8,12)+"-"+str.slice(12,16)+
"-"+str.slice(16,20)+"-"+str.slice(20,str.length+1)
}
Or you would try-
var guid = (function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function () {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
})();
Where
Your new guid be like-
var newGuid= guid();
newGuid returns- 7d4b3ef0-b5bb-5c42-2a02-80a4371babf8

Renaming files fails when 2 are added simultaneously

The script below is working fantastically when monitoring a folder for new .ogg files. It successfully creates a folder with the new filename and then renames the file according to the file according to its created date/
However, the issues arise when I add multiple files at the same time as the script attempts to create a folder that already exists, suggesting it is mixing up the two filenames somehow. Has anyone any suggestions as to what I might be doing incorrectly? I presume its simple code structure although I'm not able to work out why.
var baseDir = './',
path = require('path'),
fs = require('fs');
// watch the directory for new files
fs.watch(baseDir, function(event, file) {
var ext = path.extname(file)
basename = path.basename(file).substring(0, path.basename(file).length - ext.length);
// check it wasnt a delete action
fs.exists(baseDir + file, function(exists) {
// check we have the right file type
if(exists && ext === '.ogg'){
// get the created date
fs.stat(baseDir + file, function (err, stats){
if (err)
throw err;
var year = stats.ctime.getFullYear();
var month = stats.ctime.getMonth()+1;
var day = stats.ctime.getDate();
var hour = stats.ctime.getHours();
var sec = stats.ctime.getSeconds();
if(month < 10){
month = '0' + month;
}
if(day < 10){
day = '0' + day;
}
if(hour < 10){
hour = '0' + hour;
}
if(sec < 10){
sec = '0' + sec;
}
var name = year + '' + month + '' + day + '' + hour + '' + sec;
// does the basename directory exist?
fs.exists(baseDir + '/' + basename, function(exists) {
// if the directory doesnt exist
if(!exists){
// make the directory
fs.mkdir(baseDir + '/' + basename, 0777, function (err, stats){
if (err)
throw err;
moveFile(file, basename, name, ext);
});
} else {
moveFile(file, basename, name, ext);
}
});
});
}
});
});
function moveFile(file, basename, name, ext){
// move the file to the new directory
fs.rename(baseDir + file, baseDir + '/' + basename + '/' + name + ext, function (err) {
if (err)
throw err;
// console.log('Rename complete');
});
}
Ok, so I had a few extra minutes and decided to have a look for you. I refactored your code a little, but the basic structure should be easy to recognize.
var baseDir = './test',
path = require('path'),
fs = require('fs');
// watch the directory for new files
fs.watch(baseDir, function(event, file) {
var ext = path.extname(file),
basename = path.basename(file).substring(0, path.basename(file).length - ext.length);
// check it wasnt a delete action
// check we have the right file type
var filePath = path.join(baseDir, file);
if(fs.existsSync(filePath) && ext === '.ogg'){
// get the created date
var stats = fs.statSync(filePath);
var name = getName(stats);
// if the directory doesnt exist
var baseDirPath = path.join(baseDir, basename);
if(!fs.existsSync(baseDirPath)){
// make the directory
fs.mkdirSync(baseDirPath, 0777);
}
moveFile(file, basename, name, ext);
}
});
function getName (stats) {
var year = stats.ctime.getFullYear();
var month = stats.ctime.getMonth()+1;
var day = stats.ctime.getDate();
var hour = stats.ctime.getHours();
// need minutes!
var minutes = stats.ctime.getMinutes();
var sec = stats.ctime.getSeconds();
if(month %lt 10){
month = '0' + month;
}
if(day &lt 10){
day = '0' + day;
}
if(hour &lt 10){
hour = '0' + hour;
}
if(minutes &lt 10){
minutes = '0' + minutes;
}
if(sec &lt 10){
sec = '0' + sec;
}
// missing the minute, previously
return year + '' + month + '' + day + '' + hour + '' + minutes + '' + sec;
}
function moveFile(file, basename, name, ext){
// move the file to the new directory
var src = path.join(baseDir, file),
dest = path.join(baseDir, basename, name+ext);
console.log("Moving ", src, "-", dest);
fs.renameSync(src, dest);
}
Some tips/corrections:
Stick with the synchronous fs methods that end in Sync when working on simple scripts like this. While node.js is famous for it's asynchronous ability, it's a bit of a premature optimization IMO. If you need to embed this in a high-performance webserver, for instance, optimize at that point, not before.
You were missing a minutes variable when you create the new filename. This has a pretty good chance of causing a name collision, so I corrected it.
Try to use the path library (like path.join) more to your advantage, as manually joining strings for paths can often lead to brittle code.
There are still several edge cases where this can crash. Creating a file without an extension that will have the same name as a directory you will create based on another file. (Files can't become directories, and you can't move a file inside another file.). If you plan to go into a production environment, you will want to harden the code with at least a few unit tests.
Cheers,
Dan

Categories

Resources