Fs: Getting folder name from reddirSync - javascript

I am trying to log all files with the file extension .js from each folder
const fs = require('fs')
const folders = fs
.readdirSync('./commands/')
for (const folder in folders) {
const files = fs
.readdirSync(`./commands/${folder}/`)
.filter(file => file.endsWith('.js'))
for (const file in files) {
console.log(file)
}
}
I Get The Error
Error: ENOENT: no such file or directory, scandir './commands/0/'
Which I Assume 0 Is The Folder's Index, However I Want The Folder's Name Instead
How Can I Return The Folder name?

for in is a loop over the property names of an object. You want for of, a loop over the values of an iterable.
for (const folder of folders) {
for (const file of files) {

Related

Load local dll with node-ffi: No such file

I try to load a local .dll according the examples on stackoverflow and node-ffi documentation.
But I get the error ENOENT: no such file or directory, open '../test/user32.dll.so'. The file is there (no exception).
The extension '.so' is added automatically. Any idea what I'm doing wrong? Is this code plattform dependent? I'm on Debian.
const path = require('path');
const fs = require('fs');
const ffi = require('ffi');
function setCursor() {
const dllFile = path.join('../test', 'user32.dll');
if (!fs.existsSync(dllFile)) {
throw (new Error('dll does not exist'));
}
const user32 = ffi.Library(dllFile, {
"SetCursorPos": [
"bool", ["int32", "int32"]
]
});
console.log(user32.SetCursorPos(0, 0));
}
setCursor();
It looks like path doesn't recognize ../test as being the parent folder. I think path.join(__dirname, '..', 'test', 'user32.dll'); should get you to the right place.

Node JS filesystem module reading directory exclude files

I have some Node JS javascript code that reads folders inside of a directory, however it's currently reading folders and files, and I just need it to read folders and can't figure out what U'm missing:
router.get('/check', (req, res) => {
fs.readdir('./directory', function(err, files) {
if (err) {
res.status(500).send({ error: { status: 500, message: 'error' } })
return
}
console.log('success')
})
})
I was thinking about doing something like files[0].length > X for instance to only show names that contain more than X characters, or filter out file extensions etc, I ideally just need directories since I have a .empty file inside.
You can check reference on documentation. readdir() will return contents of the directory. You need to filter folders or files. Simply you can call and create new array files.filter(fileName => fs.statSync(path + fileName).isFile().
ref
Update
Given sample code will filter files and folders into to seperated variables. You can implement into your project.
const fs = require('fs');
const path = require('path');
const dir = fs.readdirSync(__dirname);
const folders = dir.filter(element => fs.statSync(path.join(__dirname, element)).isDirectory());
const files = dir.filter(element => fs.statSync(path.join(__dirname, element)).isFile);
console.log('folders', folders, 'files', files);

How to apply a function from node package to all the files in a directory?

I've installed mammoth.js module which converts docx to html. I can use it with a single file.
How do I use the same module for all the files in a specific folder? I'm trying to save an output html files while keeping the original name (not the extension, of course). Probably I have to require some other packages...
The code below is for a single file from the desired directory:
var mammoth = require("mammoth");
mammoth.convertToHtml({path: "input/first.docx"}).then(function (resultObject) {
console.log('mammoth result', resultObject.value);
});
The system is win64
Something like this should work
const fs = require('fs')
const path = require('path')
const mammoth = require('mammoth')
fs.readdir('input/', (err, files) => {
files.forEach(file => {
if (path.extname(file) === '.docx') {
// If its a docx file
mammoth
.convertToHtml({ path: `input/${file}` })
.then(function(resultObject) {
// Now get the basename of the filename
const filename = path.basename(file)
// Replace output/ with where you want the file
fs.writeFile(`output/${filename}.html`, resultObject.value, function (err) {
if (err) return console.log(err);
});
})
}
})
})

How to run(sync) multiple .js files from a directory

I'm trying to run multiple .js files from a directory:
exampleDir/test.js
console.log('hi');
run.js
const fs = require('fs');
const {execFileSync} = require('child_process');
const testsFolder = './exampleDir/';
const files = fs.readdirSync(testsFolder);
const funcs = files.map(function(file) {
const out = execFileSync(`node ${testsFolder}${file}`);
console.log(out.toString());
});
however I get:
> example#1.0.0 test /home/perdugames/example
> node ./run.js
child_process.js:624
throw err;
^
Error: spawnSync node ./exampleDir/test.js ENOENT
...
File paths should be specified unambiguously, preferably independent of current working directory and relative to current module. To create a new Node process, there are spawn and spawnSync in child_process:
...
const path = require('path');
const testsFolder = path.join(__dirname, './exampleDir/');
const files = fs.readdirSync(testsFolder);
const funcs = files.map(function(file) {
const filePath = path.join(testsFolder, file);
const out = spawnSync(filePath);
console.log(out.stdout.toString());
});

How do you get a list of files in a directory with javascript in html on server side?

I am trying to get an array of file names from a server side folder in javascript, how do you do this or are you not able to do this at all? I'm looking for something like this:
var file_names = get_files_by_dir(path)
Using node's asynchronous readdir() method (docs)
function getFiles(folder){
const testFolder = folder;
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
console.log(file);
});
});
}

Categories