Select all js files inside src folder (glob) - node.js

const glob = require('glob')
glob('src/**/**/**/**/**/**/**/***.js', {}, function(err, files) {})
istead of writing string like above src/**/**/**/**/**/**/**/***.js, I want to make it shorter and work similar way, but take any deep that can be inside of src folder. How can I achieve it ?

Related

NodeJS/fs.readdir - Ignore certain subdirectories when scanning for a specific set of subdirectories (closed)

Say we have a working directory containing subdirectories like so:
<workDir>
|— UselessFolder
|— NotThisFolder
|— SkipThisFolder
|— UsefulFolder
|— UsefulFolder2
|— UsefulFolder3
Is there a way that I can ignore the UselessFolder, NotThisFolder & SkipThisFolder subdirectories while scanning the working directory with fs.readdir?
The goal of the function that requires this, is to find the very last instance of the UsefulFolder subdirectories and do work with them later on. The function works fine most of the time, but it breaks in some cases due to the subfolders that I want to ignore that were stated above, I know this because if I completely remove the subfolders I want my function to ignore, the function will work fine, but in my case I can't delete any of the subdirectories within the working directory, so the only option is to ignore the ones I don't care about.
The code I'm currently using in my function to read the working directory and list its subdirectories is the following:
var workDir = '/home/user/workDir';
fs.readdir(workDir, { withFileTypes: true }, (error, files) => {
if (error) {
console.log('An error occured while reading the working directory! \n\n')
console.log('Reason: ' + error);
return;
} else {
var folderList = files
.filter((item) => item.isDirectory())
.map((item) => item.name);
console.log(folderList);
};
});
I'm not aware of a way to ask readdir itself to give you a filtered list. You will need to filter them yourself, something like this:
let unwantedDirs = ['foo', 'bar'];
var folderList = files
.filter((item) =>
item.isDirectory() &&
!(unwantedDirs.includes(item.name)))

JSON file not found

I have a json file with the name of email_templates.json placed in the same folder as my js file bootstrap.js. when I try to read the file I get an error.
no such file or directory, open './email_templates.json'
bootstrap.js
"use strict";
const fs = require('fs');
module.exports = async () => {
const { config } = JSON.parse(fs.readFileSync('./email_templates.json'));
console.log(config);
};
email_templates.json
[
{
"name":"vla",
"subject":"test template",
"path": ""
}
]
I am using VS code , for some reason VS code doesnt autocomplete the path as well which is confusing for me.Does anyone know why it is doing this?
Node v:14*
A possible solution is to get the full path (right from C:\, for example, if you are on Windows).
To do this, you first need to import path in your code.
const path = require("path");
Next, we need to join the directory in which the JavaScript file is in and the JSON filename. To do this, we will use the code below.
const jsonPath = path.resolve(__dirname, "email_templates.json");
The resolve() function basically mixes the two paths together to make one complete, valid path.
Finally, you can use this path to pass into readFileSync().
fs.readFileSync(jsonPath);
This should help with finding the path, if the issue was that it didn't like the relative path. The absolute path may help it find the file.
In conclusion, this solution should help with finding the path.

How to delete all files and subdirectories in a directory with Node.js

I am working with node.js and need to empty a folder. I read a lot of deleting files or folders. But I didn't find answers, how to delete all files AND folders in my folder Test, without deleting my folder Test` itself.
I try to find a solution with fs or extra-fs. Happy for some help!
EDIT 1: Hey #Harald, you should use the del library that #ziishaned posted above. Because it's much more clean and scalable. And use my answer to learn how it works under the hood :)
EDIT: 2 (Dec 26 2021): I didn't know that there is a fs method named fs.rm that you can use to accomplish the task with just one line of code.
fs.rm(path_to_delete, { recursive: true }, callback)
// or use the synchronous version
fs.rmSync(path_to_delete, { recursive: true })
The above code is analogous to the linux shell command: rm -r path_to_delete.
We use fs.unlink and fs.rmdir to remove files and empty directories respectively. To check if a path represents a directory we can use fs.stat().
So we've to list all the contents in your test directory and remove them one by one.
By the way, I'll be using the synchronous version of fs methods mentioned above (e.g., fs.readdirSync instead of fs.readdir) to make my code simple. But if you're writing a production application then you should use asynchronous version of all the fs methods. I leave it up to you to read the docs here Node.js v14.18.1 File System documentation.
const fs = require("fs");
const path = require("path");
const DIR_TO_CLEAR = "./trash";
emptyDir(DIR_TO_CLEAR);
function emptyDir(dirPath) {
const dirContents = fs.readdirSync(dirPath); // List dir content
for (const fileOrDirPath of dirContents) {
try {
// Get Full path
const fullPath = path.join(dirPath, fileOrDirPath);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
// It's a sub directory
if (fs.readdirSync(fullPath).length) emptyDir(fullPath);
// If the dir is not empty then remove it's contents too(recursively)
fs.rmdirSync(fullPath);
} else fs.unlinkSync(fullPath); // It's a file
} catch (ex) {
console.error(ex.message);
}
}
}
Feel free to ask me if you don't understand anything in the code above :)
You can use del package to delete files and folder within a directory recursively without deleting the parent directory:
Install the required dependency:
npm install del
Use below code to delete subdirectories or files within Test directory without deleting Test directory itself:
const del = require("del");
del.sync(['Test/**', '!Test']);

Can Gulp overwrite all src files?

Let's say I want to replace the version number in a bunch of files, many of which live in subdirectories. I will pipe the files through gulp-replace to run the regex-replace function; but I will ultimately want to overwrite all the original files.
The task might look something like this:
gulp.src([
'./bower.json',
'./package.json',
'./docs/content/data.yml',
/* ...and so on... */
])
.pipe(replace(/* ...replacement... */))
.pipe(gulp.dest(/* I DONT KNOW */);
So how can I end it so that each src file just overwrites itself, at its original location? Is there something I can pass to gulp.dest() that will do this?
I can think of two solutions:
Add an option for base to your gulp.src like so:
gulp.src([...files...], {base: './'}).pipe(...)...
This will tell gulp to preserve the entire relative path. Then pass './' into gulp.dest() to overwrite the original files. (Note: this is untested, you should make sure you have a backup in case it doesn't work.)
Use functions. Gulp's just JavaScript, so you can do this:
[...files...].forEach(function(file) {
var path = require('path');
gulp.src(file).pipe(rename(...)).pipe(gulp.dest(path.dirname(file)));
}
If you need to run these asynchronously, the first will be much easier, as you'll need to use something like event-stream.merge and map the streams into an array. It would look like
var es = require('event-stream');
...
var streams = [...files...].map(function(file) {
// the same function from above, with a return
return gulp.src(file) ...
};
return es.merge.apply(es, streams);
Tell gulp to write to the base directory of the file in question, just like so:
.pipe(
gulp.dest(function(data){
console.log("Writing to directory: " + data.base);
return data.base;
})
)
(The data argument is a vinyl file object)
The advantage of this approach is that if your have files from multiple sources each nested at different levels of the file structure, this approach allows you to overwrite each file correctly. (As apposed to set one base directory in the upstream of your pipe chain)
if you are using gulp-rename, here's another workaround:
var rename = require('gulp-rename');
...
function copyFile(source, target){
gulp.src(source)
.pipe(rename(target))
.pipe(gulp.dest("./"));
}
copyFile("src/js/app.js","dist/js/app.js");
and if you want source and target to be absolute paths,
var rename = require('gulp-rename');
...
function copyFile(source, target){
gulp.src(source.replace(__dirname,"."))
.pipe(rename(target.replace(__dirname,".")))
.pipe(gulp.dest("./"));
}
copyFile("/Users/me/Documents/Sites/app/src/js/app.js","/Users/me/Documents/Sites/app/dist/js/app.js");
I am not sure why people complicate it but by just starting your Destination path with "./" does the job.
Say path is 'dist/css' Then you would use it like this
.pipe(gulp.dest("./dist/css"));
That's it, I use this approach on everyone of my projects.

How to rename all files in a folder using gulp js?

I have a bunch of html files in a partials directory. Using gulp js, I want to minify and rename these files to .min.html. Please show me how to achieve this.
See here, using gulp-rename, if you just want to rename the files.
Something in the line of below should do:
var rename = require('gulp-rename');
gulp.src("./partials/**/*.hmtl")
.pipe(rename(function (path) {
path.suffix += ".min";
}))
.pipe(gulp.dest("./dist"));
In order to minify, you can use gulp-htmlmin. Pretty straightforward from the documentation:
var htmlmin = require('gulp-htmlmin');
gulp.task('compress', function() {
gulp.src('./partials/**/*.html')
.pipe(htmlmin())
.pipe(gulp.dest('dist'))
});
You can certainly combine the two to obtain the desired effect.

Resources