How to check the access rights of a folder - javascript

I am trying to process some directories under a specific path. one of the directories contains some folders. actually, i do not have
access to all these folders, because some of them are my own and the others belong to other users.
my question is, is there any way in javascript to check the access rights of a specific folder? because what I want to do is, to check first if I have
access to open and see the contents of that folder or not. if I have access to it, then the logic will continue. if i do not have the right to open that
folder, then i will do something else.
please let me know how to check the my access rights of a folder or a file
Note:
I am using Ubuntu

try this
var fs = require('fs');
fs.access(__dirname, fs.constants.R_OK, function(err) {
if(err){
console.error("can't read");
process.exit(1);
}
console.log("can read");
process.exit(0);
});
same way you can check for write and executable access
you can find the documentation here

You can use fs for your task
var file= 'test.text'
// Check if the file exists in the current directory.
fs.access(file, fs.constants.F_OK, (err) => {
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});
// Check if the file is readable.
fs.access(file, fs.constants.R_OK, (err) => {
console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
});
// Check if the file is writable.
fs.access(file, fs.constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
});
// Check if the file exists in the current directory, and if it is writable.
fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => {
if (err) {
console.error(
`${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);
} else {
console.log(`${file} exists, and it is writable`);
}
});
More details

Related

Is there a better way to call a .env file exists check function in cypress?

I would like to check if there is a .env file exists in the root folder before running the test. I have added below function in the index.js but it is not checking if the file exists. Could someone please advise the issue here ?
cypress/ plugins/ index.js
const filePath = "../../../.env";
module.exports = (on, config) => {
on('file:preprocessor', cucumber()),
on('before:browser:launch', (browser, launchOptions) => {
console.log("Print browser name: "+browser.name);
fileCheck(filePath); // calling the function here
});
};
function fileCheck(filePath) => {
try {
if (fs.existsSync(filePath)) {
console.log("Awesome ! .env file exists in the root directory ! ");
}
} catch(err) {
console.error(err)
console.log("Oh !, .env file is missing, please add !");
}
}
Maybe it's enough to check it in a before action, then you can do:
before(() => {
cy.on('fail', (error) => {
error.message = 'Oh !, .env file is missing, please add !';
throw error;
})
cy.readFile('.env', {timeout: 50}).should('exist');
});

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')
}
});

Why React Native RNFS's copyFile() cannot access to existing file on iOS?

I'm trying to access and copy a file from "/Documents" folder (on ios simulator) with RNFS but while .exists() can find the file, .copyFile() returns error as "The file 'temp.jpg' doesn't exists"
Why that can happen?
Here is my source file path (and also I can access it with image components):
Also adding "file://" to path doesn't work too.
/Users/myusername/Library/Developer/CoreSimulator/Devices/D305Z9A4-6C67-4DFE-A07D-1EF4D0302B87/data/Containers/Data/Application/B933EF45-391F-4882-986F-92B5430823D0/Documents/temp.jpg
Here is my code snippet, newlyCroppedImagePath is the path above. exists() returns correct result but .copyFile() returns "doesn't exists"
RNFS.exists(newlyCroppedImagePath)
.then((success) => {
console.log('File Exists!'); // <--- here RNFS can read the file and returns this
})
.catch((err) => {
console.log("Exists Error: " + err.message);
});
RNFS.copyFile(newlyCroppedImagePath, tmpFilePath)
.then((success) => {
console.log('file moved!');
})
.catch((err) => {
console.log("Error: " + err.message); // <--- but copyFile returns "doesn't exists" error for temp.jpg
});
Getting true on
RNFS.exists(newlyCroppedImagePath).then((success) => {
console.log('File Exists!'); // <--- here RNFS can read the file and returns this
})
doesn't mean that the file exists.
Since the exists() returns a Promise, the if condition will always be true.
Try the following
RNFS.exists(filePath).then((status)=>{
if(status){
console.log('Yay! File exists')
} else {
console.log('File not exists')
}
})
Also, please check the available files in the directory by using RNFS.readDir() to check whether your file has been presented or not.
Refer
https://github.com/itinance/react-native-fs#readdirdirpath-string-promisestring

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.

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

Categories

Resources