Remove file Synchronously can't find file - node.js

I have this function that make a directory have same files as the other one, so one directory is the source and the other is the one that should look like it so it removes files found in the second one that doesn't exist in the src. Anyway the thing is in the function below if I replaced fs.rmdirSyncwith fs.rmdir it works but if I don't it returns the error shown below.
function (srcDir, similarDir){
srcDir = path.resolve(process.cwd(),srcDir);
similarDir = path.resolve(process.cwd(),similarDir);
var info = {deletedFiles : 0, deletedDir : 0};
dive(similarDir,function(err, file){
if(err){
console.log(err.toString())
}
else
{
var baseFile = path.basename(file,'.css');
var srcFileDir = path.dirname(file).replace(similarDir,srcDir)
var srcFilePath = path.resolve(srcFileDir , baseFile);
if(!fs.existsSync(srcFilePath)){
console.log("before");
try {
fs.rmdirSync(file)
}
catch(error){
console.log(error)
}
console.log("after");
info.deletedFiles++;
}
}
})
This is the error that occurs when I use fs.rmdirsync although the file does exist and If i changed it to fs.rmdir it works ( on windows os )
{ [Error: ENOENT, no such file or directory 'D:\angularjs\build\css\components\test\test\test.css']
errno: 34,
code: 'ENOENT',
path: 'D:\\angularjs\\build\\css\\components\\test\\test\\test.css',
syscall: 'rmdir' }

Try upgrading to fs-extra, fs.removeSync() works without issue.

Related

Error writing a file using 'fs' in Node

I'm trying to write to a file using the following function:
function writeFile (data, callback) {
var fs = require('fs');
var now = new Date();
fs.writeFile(now.toISOString() + ".json", data, function(err) {
if (err) {
return console.log(err);
} else {
console.log(true);
}
});
}
but im getting an error like this:
{ Error: ENOENT: no such file or directory, open 'C:\Users\Ruslan\WebstormProjects\communication-system\client\6\28\2017_19:47:55.json'
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\Users\\Me\\WebstormProjects\\blah-blah\\client\\6\\28\\2017_19:47:55.json' }
I'm trying to create a file every time I run the program, but that doesn't seem to work very well because it says file does not exist. Is there anything im doing wrong? BTW, im running this on windows
EDIT: It was indeed wrong file name that was bugging the saving process
When you call fs.writeFile() you have to pass it a filename/path:
Where the parent directory in the path already exists.
Where the path/filename contains only characters that are legal for your OS.
It appears you are likely failing both of these unless you've pre-created the directory: C:\Users\Ruslan\WebstormProjects\communication-system\client\6\28. And, if this is running on Windows, then you also can't use : in a filename.
Assume you actually want the path to be C:\Users\Ruslan\WebstormProjects\communication-system\client and what the filename to be based on your now.toISOString(), the usual work-around is to replace path separators and other invalid filename characters with safe characters to you convert your now.toISOString() to something that is always a safe filename. In this case, you could do this:
// replace forward and back slashes and colons with an underscore
// to make sure this is a legal OS filename
let filename = now.toISOString().replace(/[\/\\:]/g, "_") + ".json";
fs.writeFile(filename, ....)

Renaming multiple files asyncroniosly causing error in Node.js

I am trying to rename a bunch of pre-generated testing files (1000+) asynchronously in Node.js.
The code looks like the following:
const fs = require('fs')
const { each } = require('async')
each(files, file => {
let newfile = 'new' + file
fs.rename(file, newfile, err => {
err ? console.log(err) : console.log('renamed')
}
})
This leads to following error:
Uncaught Error: ENOENT: no such file or directory, lstat '8d3320e35d22772f'
at fs.lstatSync (fs.js:902:18)
at Object.fs.lstatSync
It's not async module issue, since replacing each with native forEach leads to the same error. Also, there are no issues when using synchronous version of rename fs.renameSync.
I think it's trying to move some file twice or so but can't figure where exactly mistake is. Made this assumption, because all files have been already renamed successfully and very likely error generated afterward. Can someone advice what causing such behavior?
My bad. Just in case someone curious, this error came from following underlying function:
function rmDir(dir) {
var list = fs.readdirSync(dir);
for(var i = 0; i < list.length; i++) {
var dirOrFile = path.join(dir, list[i]);
var stat = fs.lstatSync(dirOrFile);
if(dirOrFile == "." || dirOrFile == "..") {
// pass these files
} else if (stat.isDirectory()) {
// rmdir recursively
rmDir(dirOrFile);
}
// else { fs.unlinkSync(dirOrFile) } // rm fiilename
}
fs.rmdirSync(dir);
}

Node.js fs.stat not working as expected when used on module

i'm having a weird issue with fs.stat to check if a file is valid or not,
when i pass an absolute path with a variable (filePath in this case)
it appends the path of the project to the path i sent!
FileCompresser.CompressFile = (filePath,callback) =>{
console.log(filePath);
fs.stat(filePath,(err,stat)=>{
if(err){
callback(err,null);
return;
}
var readStream = fs.createReadStream(filePath).pipe(zlib.createGzip());
callback(null,readStream);
});
}
AssertionError: expected Error {
code: 'ENOENT',
errno: -4058,
path: 'C:\\carpetica\\NodeCompress\\‪‪C:\\carpetica\\delete.reg',
syscall: 'stat',
message: 'ENOENT: no such file or directory, stat \'C:\\carpetica\\NodeCompress\\‪‪C:\\carpetica\\delete.reg\''
} to not exist
yet if i do the following it works correctly :
fs.stat("C:/carpetica/delete.reg",(err,stat)=>{
if(err){
callback(err,null);
return;
}
var readStream = fs.createReadStream(filePath).pipe(zlib.createGzip());
callback(null,readStream);
});
but of course that is not good for testing... i send exactly the same value i hard coded there... yet i get that weird behavior.. this behavior doesn't happen when i run directly from the REPL without modules.
UPDATE:
found the culprit ( i think!), i tested with 2 paths, and the only thing different were the
' and the "" surrounding the strings
it("should return a compressed file",(done)=>{
var path2 = '‪F:/ISOS/linuxmint-17.1-mate-64bit.iso';//this doesnt work!
var path1 = "C:/carpetica/delete.reg";//but this does!
FileCompresser.CompressFile(path2, (err,CompressedfileStream) =>{
should.not.exists(err);
should(CompressedfileStream).be.ok();
done();
});
} );
as soon as i wrapped path2 on double quotes it worked as intended :)

NodeJS: readdir() returns "undefined" instead of the list of files?

I'm trying to check how many files does have a directory using NodeJS's File System.
var fs =require('fs');
function listaArchivos(directorio){
fs.readdir(directorio, function(err, archivos){
if(!err) {
console.log(archivos);
} else {console.log(err)}
})
}
var directorio = 'home/Rosamunda/Desktop/coderhouse/fs/';
listaArchivos(directorio);
I receive this error:
{ [Error: ENOENT, readdir 'home/Rosamunda/Desktop/coderhouse/fs/']
errno: 34,
code: 'ENOENT',
path: 'home/Rosamunda/Desktop/coderhouse/fs/' }
I've tried to search for that ENOENT error, and what I do understand is that the error appears when the path is incorrect, but the path does exist. If I try to print archivos, it returns "undefined".
ENOENT means the path doesn't exist. It looks like you may be missing the / at the beginning of the path (to make it an absolute path).

node.js fs rename ENOENT

I am trying to write a handler for file uploads in node.js using express framework. Following is the raw skeleton of it.
exports.handleUpload = function(req,res){
var temp_path = req.files.doc.path,
target_path = './uploads/' + req.files.doc.name ;
fs.rename(temp_path, target_path, function(err){
if(err){
console.log(err);
}
fs.unlink(temp_path, function(){
if(err){
console.log(err)
}
})
//Do stuff
})
}
However I get an error in the execution of renmae function occassionally(not always), especially with uploads of large files.
This is what the console caches from the error code
{ [Error: ENOENT, rename '/tmp/16368-19661hu.pptx'] errno: 34, code: 'ENOENT', path: '/tmp/16368-19661hu.pptx' }
From : https://github.com/joyent/node/blob/master/deps/uv/include/uv.h
XX(ENOENT, "no such file or directory")
The uploads/ directory does exist and permissions isn't an issue. Had it been so, it would have been failing each time, but it does not.
You're using the /tmp directory. The OS might be deleting the files since it can do so for the /tmp directory, hence the "randomness" of the issue. Use fs.exists before doing your other operations.

Resources