I am looking for a way to delete folders that contain files in node.js ?
I know there exists a way to delete empty folders using fs.rmdir(), and i tried using the npm rimraf module that provides the function "rm -rf" for node.js
socket.on("end", function (data) {
rimraf("./a/b/c", function(err){
if(err){
console.log(err);
}
});
});
but i keep getting this error.
{ [Error: ENOTEMPTY: directory not empty, rmdir './a/b/c']
errno: -39,
code: 'ENOTEMPTY',
syscall: 'rmdir',
path: './a/b/c' }
So I tried another way around this issue, first i empty the directory then i delete the directory
socket.on("end", function (data) {
rimraf("./a/b/c/*", function(err){
if(err){
console.log(err);
}else{
fs.rmdir("./a/b/c")
}
});
});
but then i get this error
Error: ENOTEMPTY: directory not empty, rmdir './a/b/c'
at Error (native)
I checked the folders the rimraf deletes the files but i don't see why i am still getting an error with fs.rmdir().
Edit :
I looked up a different module called fs-extra and came up with this.
fse.emptyDir("a/b/c/", function(err){
if(err){
console.log(err);
} else {
console.log("doneaaaa")
fse.remove("a/b/c",function(err){
if(err){
console.log(err);
} else {
console.log('doneaswell');
}
});
}
});
Now i get this error :
doneaaaa
{ [Error: EBUSY: resource busy or locked, unlink 'a/b/c/.nfs000000002ab5000d00000072']
errno: -16,
code: 'EBUSY',
syscall: 'unlink',
path: 'a/b/c/.nfs000000002ab5000d00000072' }
As you can see i get the past the first part of the function that deletes the files from the folder but when it comes to deleting the folder it throws the EBUSY error.
Thank you in advance !
Regardin the EBUSY error, do one thing. Do console.log(process.cwd()) to see what directory Node process is in before it tries to delete the folder. If Node is in the same folder it is trying to delete, then it will issue the EBUSY error. I had that happen to me in a Node.js application I'm developing. The solution was to change directory (process.chdir(new directory)) to something other than the one I'm trying to delete before I attempt to delete it, and problem solved. This happened on Windows by the way.
To remove it syncronously:
var fs = require('fs');
var deleteFolderRecursive = function(path) {
if( fs.existsSync(path) ) {
fs.readdirSync(path).forEach(function(file,index){
var curPath = path + "/" + file;
if(fs.lstatSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};
Related
I have a file system function which deletes a file then creates a new one with all new data, I am looking for a possible fix for an error that occurs randomly, and not every time, but around every other time. Here is my current code:
try {
if(fs.existsSync(file)) {
fs.unlink(file, function (err) {});
}
} catch (error){
console.log('There was no file to be deleted');
}
fs.open(file, 'w', function (err, file) {
if (err) throw err;
});
var logger = fs.createWriteStream(file, {
flags: 'a' // 'a' means appending (old data will be preserved)
});
which throws the error occasionally:
C:\Users\codel\OneDrive\Documents\BattlEye\index.js:265
if (err) throw err;
^
Error: EPERM: operation not permitted, open 'C:\Users\codel\OneDrive\Documents\BattlEye\files\610636905440215071.txt'
Emitted 'error' event on WriteStream instance at:
at internal/fs/streams.js:375:14
at FSReqCallback.oncomplete (fs.js:171:23) {
errno: -4048,
code: 'EPERM',
syscall: 'open',
path: 'C:\\Users\\codel\\OneDrive\\Documents\\BattlEye\\files\\610636905440215071.txt'
}
First thing that is noticeable is that this is a cloud drive(OneDrive). With my lack of knowledge about permissions, I decided to test out if the problem was in the OneDrive by transferrring the file to my harddrive. The results were not surprising. It didn't change a thing.
C:\Users\codel\Documents\BattlEye\index.js:265
if (err) throw err;
^
[Error: EPERM: operation not permitted, open 'C:\Users\codel\Documents\BattlEye\files\610636905440215071.txt'] {
errno: -4048,
code: 'EPERM',
syscall: 'open',
path: 'C:\\Users\\codel\\Documents\\BattlEye\\files\\610636905440215071.txt'
}
But the Emmitted 'error' event on WriteStream disappeared from the error log.
Any ideas on why this error is happening and how to fix it?
It looks like you're using asychronous fs calls. Async calls do not work like that.
You can do a search for NodeJS asynchronous programming.
The line of code below throws a EPERM error with errno: 4048 on windows
fs.rename('/code/App/temp/tmp', '/code/App/temp/temp', (err) => {
if (err) return console.log(err);
});
Actually i used the code (with altered paths) to rename the last folder from 'temp' to 'tmp' earlier and it succeeded.
The same set of permissions exist for that folder before and after renaming it.
why does it fail when i run code to revert back to the original name ?
For some reason, I need to modify my mongodb with brute force.
the expected data is in a file, and I need to update the mongodb's value by the read-out file stream. with node.js' help, I generate codes like this,
const fs = require('fs');
fs.open('./f.csv', 'r', (err, fd) => {
if(!err) {
fs.readFile('./server/f.csv', 'utf8', (err,data)=>{console.log(data);});
}
});
But, now I have a difficulty to find the file. the execution throws an error:
{ Error: ENOENT: no such file or directory, open './f.csv' errno: -2, code: 'ENOENT', syscall: 'open', path: './f.csv' }
I have tried to locate the file in the Meteor's public folder or server folder, which is also Meteor's backend, but the efforts are in vain. So how to make the codes find the file on Meteor's backend?
Any suggestion is welcome.
Easiest solution is to put the file in /private and access it using the Assets module:
https://docs.meteor.com/api/assets.html
Example: If you put the file in /private/f.csv
const data = Assets.getText('f.csv');
console.log(data)
// ... Do something with that data
I am using this block of code to create and write a new directory and a file.
I just started to learn nodejs
var lib = {};
lib.baseDir = path.join(__dirname,'/../.data/');
lib.create = function(dir,file,data,callback){
fs.open(lib.baseDir+dir+'/'+file+'.json', 'wx', function(err, fileDescriptor){
if(!err && fileDescriptor){
var stringData = JSON.stringify(data);
// Write to file and close it
fs.writeFile(fileDescriptor, stringData,function(err){
if(!err){
fs.close(fileDescriptor,function(err){
if(!err){
callback(false);
} else {
callback('Error closing new file');
}
});
} else {
callback('Error writing to new file'+'lib.baseDir');
}
});
} else {
callback(err);
}
});
};
but I am repeatedly getting the error
{ Error: ENOENT: no such file or directory, open 'C:\Users\Jawahr\Documents\GitHub\node-api\.data\test\newFile.json'
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\Users\\Jawahr\\Documents\\GitHub\\node-
api\\.data\\test\\newFile.json' }
calling this library in a index.js as
var _data = require('./lib/data');
_data.create('test','newFile', {"asdksadlk" : "asldj"} ,function(err) {
console.log('this was the error ',err);
});
I've been stuck here for a while, is it because the pathname and filename contained the part "C:" which has colon a reserved char in windows 10, if it is the problem how to solve this.
using windows 10 and NodeJs 8.6.
Can you try this -
fs.open(lib.baseDir+dir+'/'+file+'.json', 'w', function(err, fileDescriptor){
It looks like 'wx' throws an error if file exists -
'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
'wx' - Like 'w' but fails if the path exists.
'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
'wx+' - Like 'w+' but fails if the path exists.
Referred from here
Looks like your put non-existing or non-accessible path to your file. Look:
fs.open('/path/is/not/exists/xx.js','wx',(err,fd)=>{
if (err) {
console.log(err.message);
}
});
and got
Error: ENOENT: no such file or directory, open '/path/is/not/exists/xx.js'
In case when file is already exists you will got something like Error: EEXIST: file already exists, open '...'
And last, but not least. Instead of lib.baseDir+dir+'/'+file+'.json' better solution is use path.join(lib.baseDir,dir,file+'.json') from path module
Add a check for directory or create before fs.open
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
Then the rest of your code will work. as fs.open only creates file if it doesn't exist, it does not create directory
I'm using the html-pdf module to generate pdfs, using the following code:
var ejs = require('ejs');
var fs = require('fs');
var pdf = require('html-pdf');
var build = function (template, data) {
var html = ejs.compile(fs.readFileSync(template, 'utf8'));
html = html(data);
return html;
}
pdf.create(build('views/print_templates/pm_export_pdf.ejs',
{rows:resolve(rows, user_rows, table_rows,
subproject_rows, milestone_rows, release_rows)}), pdfconfig)
.toFile(function (err, pdf) {
if (err)
return console.log(err);
res.sendFile(pdf.filename);
});
PDFconfig is the config variable for html-pdf. And resolve is my own db resolve function, which is not very relevant in this story.
When I run this locally on OSX 10.10 on my MacBook Pro this works like a charm. But when I run this on my server(centOS), I get the following error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at errnoException (net.js:904:11)
at Object.afterWrite (net.js:720:19)
Has this something to do with permissions maybe? I'm not really sure what I'm doing wrong..
I run the following versions:
Node: 0.10.31
Express: 4.10.7
html-pdf: 1.2.0
For future purposes:
I figured that I had to rebuild my node-modules. I think I accidentally copied the node-modules folder over to the test server on centOS, and phantomjs had build it's dependencies for OSX. I'm still not sure how the error that it threw correspondents with that, but it fixed it.
Also be sure that you have FreeType and fontconfiglib installed.