Node globby error while using multi patterns - javascript

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){...})

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"

Error: ENOENT: no such file or directory

I am trying to get get the folder path from user's selection and for each file I read it and return the data. However upon getting the file I cannot read the data for some reason that I have't been able to understand yet. The directory I am trying to read and render do exist. I have referred to the other similar posts as well.
readFolder() {
dialog.showOpenDialog({ properties: ['openDirectory'] }, (dirFiles) => {
console.log(dirFiles);
if (dirFiles === undefined) {
console.log('No file ');
return;
}
const pathName = dirFiles[0];
fs.readdir(pathName, (err, files) => {
files.forEach(file => {
fs.readFile(file, 'utf-8', (err, data) => {
if (err) {
console.log(`something went wrong ${err}`);
} else {
console.log(data);
}
});
});
});
});
}
readdir returns filenames "a", "b", "c" etc. You want pathName + '/' + file for "/path/to/file/a"
The mistake I made was the fact that I hadn't realised the return values of 'file' which are just the names of the files as strings but not paths. Assinging let filePath =${pathName}/${file}; and reading it onwards solved the problem.

delete all files in folder

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.

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