I need to delete only the json files within a directory (multiple levels). I'd hazard a guess that it's possible with fs-unlinkSync(path)
But I can't find a solution without specifying the individual file name.
I was hoping to solve it with the following...
fs.unlinkSync('./desktop/directory/*.json')
but unfortunately the asterisk wouldn't select all. Any suggestion please?
You can list files using fs.readdirSync, then call fs.unlinkSync to delete. This can be called recursively to traverse an entire tree.
const fs = require("fs");
const path = require("path");
function deleteRecursively(dir, pattern) {
let files = fs.readdirSync(dir).map(file => path.join(dir, file));
for(let file of files) {
const stat = fs.statSync(file);
if (stat.isDirectory()) {
deleteRecursively(file, pattern);
} else {
if (pattern.test(file)) {
console.log(`Deleting file: ${file}...`);
// Uncomment the next line once you're happy with the files being logged!
try {
//fs.unlinkSync(file);
} catch (err) {
console.error(`An error occurred deleting file ${file}: ${err.message}`);
}
}
}
}
}
deleteRecursively('./some_dir', /\.json$/);
I've actually left the line that deletes the file commented out.. I'd suggest you run the script and be happy the files that are logged are the right ones. Then just uncomment the fs.unlinkSync line to delete the files.
Related
So the thing is that, I'm storing files of other guys on my server that are mp4 but I need to make sure to delete that later on but sometimes the files remain.
So I want to do something that will detect if any .mp4 file is found in the folder if yes then I can remove it using unlinkSync.
I don't know the filename, that's why I want the system to figure it out
Hope you guys can help?
You can use readDir to read all filenames in a folder. Afterwards you can check the file ending:
const testFolder = './tests/';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
console.log(file.includes(".mp4"));
});
});
I need somehow to loop over subdirectories but it returns me an error: ENOENT: no such file or directory, stat 'text3.txt'
Here are the files I use:
main.js
files
|_file1.txt
|_file2.txt
dir
|_text3.txt
Here is my main.js:
fs = require('fs'), aes = require('aes256'),
key = 'abc';
enc = file => {
return aes.encrypt(key,file)
}
decr = encr => {
return aes.decrypt(key,encr)
}
clf = dir => {
files = fs.readdirSync(dir);
// Filter files
for(let i of files){
stat = fs.statSync(i)
if(stat.isFile()){
newFiles.push(i)
}
else dirs.push(i)
}
// Encrypt folders
for(let file of newFiles){
fl = fs.readFileSync(file).toString();
fs.writeFileSync(file,enc(fl));
}
}
clf('./')
for(let c of dirs) clf(c);
Decrypt and ecnrypt func-s use aes256 encryption and return strings. Then clf function checks if files are not folders and pushes folders to an array. Then we encrypt files in main directory, but nothing happens in sub directories, it returns an error instead:
ENOENT: no such file or directory, stat 'text3.txt'
But text3.txt IS in dir directory!! Then why I have an error?
First off, declare every single variable you use. This is a recipe for disaster using undeclared variables. I would not even attempt to work on code like this without first declaring every single variable to the proper scope using let or const.
Second, when you do fs.statSync(i), the i here is just a plain filename with no path. If you do console.log(i), you will see it is only a filename. So, to reference the right file, you have to add the path back onto it from the your readdirSync(dir) and then pass that full path to fs.statSync().
You will find path.join() as a convenient way to combine a path with a filename.
I'm currently trying to search for a few files in a specific folder on Windows using node and grunt.
I have a grunt task that has a function to read a dir with JSON files, but the problem is that when I run the task, the code to read the file doesn't do anything, everything else on that grunt task runs perfect, but that. I'm not sure if the reference for the path is correct, but I'm also using path.normalize() and it does not throws any error.
This is snippet of the code:
..// Some other code
var fs = require('fs'),
path = require("path");
grunt.registerTask('separate', function() {
var filePath = path.normalize("C:\Users\jbernhardt\Desktop\testkeeper\jenkinsReports");
fs.readdir(filePath, function(err, filenames) {
//This log doesn't show as it the function is not running
grunt.log.writeln("Testing");
if (err) {
grunt.log.writeln("Error");
return;
}
filenames.forEach(function(filename){
grunt.log.writeln("Testing");
});
});
...//Some more code below for the same task
}
Does anyone has an idea why this snippet of the code is being skipped when I run the task? I could probably be missing some basic stuffs. Thanks!
Try readdirSync and check if your function still not working. I guess your process is finished before the callback.
You can simply use the __dirname object to get the path where the current script is running:
..// Some other code
var fs = require('fs'),
path = require("path");
grunt.registerTask('separate', function() {
fs.readdir(__dirname, function(err, filenames) {
//This log doesn't show as it the function is not running
grunt.log.writeln("Testing");
if (err) {
grunt.log.writeln("Error");
return;
}
filenames.forEach(function(filename){
grunt.log.writeln("Testing");
});
});
...//Some more code below for the same task
}
You can find more info here.
you need change your path
var filePath = path.normalize("C:\\Users\\jbernhardt\\Desktop\\testkeeper\\jenkinsReports");
Also To achieve consistent results when working with Windows file paths on any operating system, use path.win32:
path.win32.basename('C:\\Users\\jbernhardt\\Desktop\\testkeeper\\jenkinsReports"');
You can read about https://nodejs.org/api/path.html#path_windows_vs_posix
The slash in path are being escaped.
"C:\\Users\\jbernhardt\\Desktop\\testkeeper\\jenkinsReports"
should solve your issue.
I am trying to move files from one directory to another using the mv module. The problem is, once the files are moved, the source directory gets deleted. I dont want this, I want only the files that are moved to be deleted from the source directory. The source directory should remain (even if it is empty). Not sure how to do this with the mv module (or if there are any other options).
My code
var pathToPdf = path.join(__dirname, '../pathToPdf/');
` var intermediate = path.join(__dirname, '../intermediate/');
fs.readdir(pathToPdf, function(err, files) {
if (err) return;
files.forEach(function(file){
mv(pathToPdf, intermediate, function(err) {
if(err){
console.log("oops!")
}
});
----move code ---
This code is moving the files to intermediate directory, but the pathToPdf directory gets deleted, which I want to avoid. Please advise.
files.forEach(function(file){
console.log(file)
console.log("pathToPdf", pathToPdf+file)
mv(pathToPdf+file, intermediate+file, function(err) {
if(err){
console.log("oops!")
}
});
On Windows 7. In a proprietary app that contains chromium browser. Running on Node.js and Express. In my file 'javascripts/getMyFiles.js' I'm trying to use the following code from: http://nodeexamples.com/2012/09/28/getting-a-directory-listing-using-the-fs-module-in-node-js/
#!/usr/bin/env node
var fs = require("fs"),
path = require("path");
var p = "../"
fs.readdir(p, function (err, files) {
if (err) {
throw err;
}
files.map(function (file) {
return path.join(p, file);
}).filter(function (file) {
return fs.statSync(file).isFile();
}).forEach(function (file) {
console.log("%s (%s)", file, path.extname(file));
});
});
I have 3 problems with this code:
I get and 'Unexpected token ILLEGAL' error from the '#!/use/bin/end node' line
After deleting that first line of code I get the error 'Uncaught ReferenceError: require is not defined'. If I move the '...require...' lines to my root app.js file then the object fs is undefined in my getMyFiles.js file.
I need to specify which folder to list when my app gets an event
I get that require is not available on the client-side, but I don't want to get a list of files from the client side. The files I want to list are in the same path as all of my other files, '/public/Docs'. I can load a known file straight away, but I need to present the user with a list of available documents first. Any assistance will be most appreciated.