delete all files in folder - javascript

how to delete files in project catalogue during yeoman process?
initializing() {
this.sourceRoot('./generators/templates');
this.destinationRoot('./generators/project');
console.log(this.destinationPath());
console.log(this.sourceRoot());
this.fs.delete(this.destinationPath());
this.fs.delete(this.destinationPath('**/*'));
this.fs.delete('project');
this.fs.delete('./generators/project');
this.fs.delete('generators/project');
this.fs.delete('generators/project/**/*');
}
non of these seems to work :(

fs.readdir('path here', (err, files) => {
if (err) console.log(err);
for (const file of files) {
fs.unlink(path.join('path here', file), err => {
if (err) console.log(err);
});
}
});

If you want to delete a file using fs you should use fs.unlink(path, callback) or fs.unlinkSync(path).
// Asynchronous version
fs.unlink('file.txt', function(err) {
if(!err) {
console.log('file deleted');
}
}
// Synchronous version, deprecated
fs.unlinkSync('file.txt');
Make sure you have the newest version of node installed to make sure this is available.

Related

I would like guidance to create some directories

What I need:
Create a folder on the desktop, within that folder create another called "img" and inside img create "home".
The way I managed to do it, But I know it's not the ideal way ... I'm still learning, thank you for your patience!
Any suggestions to improve this?
var nome = 'teste';
const dir = `C:/Users/mathe/Desktop/${nome}`;
if (!fs.existsSync(dir)){
fs.mkdir(dir, (err) => {
if(err){
console.log(err)
}else{
dirImg = dir+'/'+'img';
fs.mkdirSync(dirImg)
fs.mkdirSync(dirImg+'/'+'home')
console.log('Sucess')
}
});
}else{
console.log(`File $ {name} cannot be created because it already exists!`)
}
mkdir has a recursive option, so:
if (!fs.existsSync(dir)){
fs.mkdir(`${dir}/img/home`, {recursive: true}, (err) => {
// ^^^^^^^^^^^^^^^^^−−^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−
if(err){
console.log(err)
}else{
console.log('Sucess')
}
});
}else{
console.log(`File $ {name} cannot be created because it already exists!`)
}
Side note: It's generally not a good idea to check for existence before creating. Instead, just go ahead and try to create it. From the documentation:
Calling fs.mkdir() when path is a directory that exists results in an error only when recursive is false.
So:
fs.mkdir(`${dir}/img/home`, {recursive: true}, (err) => {
// ^^^^^^^^^^^^^^^^^−−^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−
if(err){
console.log(err)
}else{
console.log('Sucess')
}
});

Error: ENOENT: no such file or directory, uv_chdir at process.chdir when creating a directory and changing into it

I'm trying to write a small app that installs some files and modules in a new folder, but I keep getting this error:
{ Error: ENOENT: no such file or directory, uv_chdir
at process.chdir (/home/aboardwithabag/LaunchProject/node_modules/graceful-fs/polyfills.js:20:9)
at cd (/home/aboardwithabag/LaunchProject/index.js:26:13)
Below is my code. Can someone help me out?
// node LaunchProject projectName
// Installs a server, node modules, and index page.
// not working due to issues with chdir.
const cp = require('child_process');
const fse = require('fs-extra');
// const path = require('path');
const project = process.argv[2];
let server ="";
let home = "";
function make (cb){
fse.mkdirs(project, function(err){
if (err){
console.error(err);
}
});
cb;
}
function cd(cb){
try{
process.chdir('/'+project);
cb;
} catch (err) {
console.error(err);
return;
}}
function install(cb){
cp.exec('npm install express', function(err){
if (err){
console.error(err);
} else {
console.log('Express Installed.');
cp.exec('npm install ejs', function(err){
if (err){
console.error(err);
} else{
console.log('Ejs Installed.');
fse.outputFile('index.js', server);
fse.outputFile('public/index.html', home);
}});
}
});
cb;
}
make(cd(install(console.log(project + ' created.'))));
unless the folder name you assign to the project variable (in this case it seems to be "uv_chdir") is located at the root folder of your HDD, below line will give the error:
process.chdir('/'+project);
make sure you give correct path to the program arguments. (in this case argv[2])
Or you may remove the leading '/' and make the path relative.
It seems there are some issues with this code.
cb callbacks provided as function arguments need to be called not after the async calls, but inside the callbacks of these calls. For example:
function make (cb){
fse.mkdirs(project, function(err){
if (err){
console.error(err);
}
cb();
});
}
The last call chain make(cd(install(console.log(project + ' created.')))); would work only with sync calls in reversed order and only if they returned needed callbacks.
That is why your new dir is not ready when you try to use it: your async functions do not actually wait for each other.
You do not call your callbacks as cb(), just mention them as cb. You should call them.
With minimal changess, your code can be refactored in this way:
'use strict';
const cp = require('child_process');
const fse = require('fs-extra');
const project = process.argv[2];
let server = '';
let home = '';
make(cd, install, () => { console.log(project + ' created.'); });
function make(cb1, cb2, cb3) {
fse.mkdirs(project, (err) => {
if (err) {
console.error(err);
}
cb1(cb2, cb3);
});
}
function cd(cb1, cb2) {
try {
process.chdir('/' + project);
cb1(cb2);
} catch (err) {
console.error(err);
}
}
function install(cb1) {
cp.exec('npm install express', (err) => {
if (err) {
console.error(err);
} else {
console.log('Express Installed.');
cp.exec('npm install ejs', (err) => {
if (err) {
console.error(err);
} else {
console.log('Ejs Installed.');
fse.outputFile('index.js', server);
fse.outputFile('public/index.html', home);
cb1();
}
});
}
});
}
But it is rather brittle and unnecessarily complicated in this form. Maybe it would be simpler to inline your functions each in other.
when I use PM2,i got this error "no such file or directory, uv_chdir"
the resolvent is :
first,I use 'pm2 delete' to delete old process
second,I use 'pm2 start',then ok
ps : just change your code or use 'pm2 reload' or 'pm2 restart' would not be ok.
more detail , you can see "https://blog.csdn.net/u013934914/article/details/51145134"

Delete files from folders on S3 bucket

After doing a lot of investigation on the Amazon S3 I have understood that emptying S3 bucket is feasible. I have a requirement where I want to delete only the selected folders from the S3 bucket. Instead of deleting all the folders at once or deleting individual folders from S3 bucket. Hope my understanding of AWS is right. I would like to have options to achieve this. Please let me know if there is a solution from javascript.
function deleteObj(x){
var params = {Bucket: bucketName, Key: x.fileName};
bucket.deleteObject(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
});
}
If s3 is anything like dynamoDB you will have to get a list of all of the items in the bucket and then loop over deleting them all individually. There's a gist here with an example script.
I was in the same condition, I didn't find any interesting answer, so i came up with my own solution. You just need to Modify the value of MaxKeys. In the below code, i am showing how we can delete a folder (Including any files under it).
Just remove "export" from below code in case you don't need it
exports.EmptyS3Folder = function(folderName){
return new Promise((resolve, reject) => {
exports.s3.listObjectsV2({
Bucket: process.env.AWS_S3_BUCKET,
Prefix: folderName,
MaxKeys: 10000000
}, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
reject(err)
} else {
if(data.Contents.length > 0){
const deleteParams = {
Bucket: process.env.AWS_S3_BUCKET,
Delete: {
Objects: [],
Quiet: false
}
};
data.Contents.forEach(function(content) {
deleteParams.Delete.Objects.push({Key: content.Key});
});
deleteParams.Delete.Objects.push({Key: folderName});
exports.s3.deleteObjects(deleteParams, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
reject(err)
} else {
resolve(data)
}
});
}else{
resolve(data)
}
}
});
})
}

Node globby error while using multi patterns

I use node glob which is working OK .
I use it for one folder1 like following
glob('folder1/*.js'), function(err, files){
if (err) {
console.log('Not able to get files from folder: ', err);
} else {
files.forEach(function (file) {
https://github.com/isaacs/node-glob
Now I want to read in one shot from folder2 also and I try to use globby like following and I got error
globby(['folder1/*.js','folder2/*.js']).then( function(err, files){
if (err) {
console.log('Not able to get files from folder: ', err);
} else {
//Get plugin configuration & provided actions
files.forEach(function (file) {
https://github.com/sindresorhus/globby
in this case the files are coming as undfiend and I got to the error any idea why
Try to remove err argument from the then callback. Use catch to handle errors
globby(['folder1/*.js','folder2/*.js']).then( function(files){...}).catch(function(err){...})

Error : Path must be a string, NodeJS Read/Write

What i'm trying to do is read/write to multiple files at once, Once a file is created, only the data inside the file would be changed.
code:
var files = fs.readdirSync(__dirname+"/")
function readWrite(files) {
fs.readFile(files[i], 'utf-8', function(err, data){
if (err){
console.log(err)
}
fs.writeFile(files[i], 'test string', 'utf-8', function (err) {
if (err){
console.log("completed")
}
})
})
}
for(i in files){
readWrite(files[i])
}
The error is pretty obvious "path must be a string", But how do I go about writing to multiple files in the same directory at once?
I'm pretty new to node, so sorry if this seems like a bonehead question, any help would be appreciated.
You're passing filename to readWrite function so you should not use [i]:
function readWrite(file) {
fs.readFile(file, 'utf-8', function(err, data) {
if (err) {
console.log(err)
}
fs.writeFile(file, 'test string', 'utf-8', function (err) {
if (err) {
console.log("completed")
}
})
})
}
for (i in files) {
readWrite(files[i])
}
Try replacing files[i] by files inside your function. You should be using the name of your variable, files (and probably rename it to filepath)
After that, do you really want to read and write from the same file at the same time (this is what your code is doing) ?

Categories

Resources