Node JS filesystem module reading directory exclude files - javascript

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

Related

how could i use require() to read a local json file by just adding the local project json file path?

This is how I managed to be able to read the json file
posts.js file
const PATH = require('/Users/jorgesisco/Dropbox/Programming_Practice/Web_Development/PWJ/Module-8/Blog/pwj-module-8-my-blog-api/exercise/data.json');
class Post {
get() {
// get posts
}
getIndividualBlog() {
// get one blog post
}
addNewPost() {
// add new post
}
readData() {
return PATH;
}
}
module.exports = Post;
Now in app.js I call the function and I am able to see the json file in postman.
// 1st import express
const express = require('express');
const app = express();
const Post = require('./api/models/posts');
const postsData = new Post();
const posts = [
{
id: '1581461442206',
title: 'This is a New Blog Post',
content: 'This is the content! ',
post_image: 'uploads/post-image-1581461442199.jpg',
added_date: '1581461442206',
},
];
// const result = posts.flatMap(Object.values);
app.get('/api/posts', (req, res) => {
res.status(200).send(postsData.readData());//here I call the function to see json file in postman
});
app.listen(3000, () => console.log('listening on http://localhost:3000'));
I think I shouldn't use the whole file path for the json file but when I just use something like ./data.json an error happen because it can't find the json file.
For accessing the files from the same dir you need to pass './'
Example: require('./data.json');
for accessing the files from one dir out from current dir '../'
Example: require('../data.json');
For accessing the files from two dir out within different folder '../../foldername/data.json'
Example: require('../../dataFolder/data.json');
The file path is referenced from the directory where you run the main code (app.js)
Move your data.json file inside the directory where your code is located. Let's say main_code/datadir. So, it looks like this now -
-- maincode
-- datadir
-- data.json
-- posts.js
-- app.js
Refer the file in posts.js code as require('./datadir/data.json')(Assuming datadir/ is in the same path/level as your app.js code)
Run app.js

Fs: Getting folder name from reddirSync

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

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

Relative path on fs.watchfile using Node.js

I use this method to read data from the file when it changes. I restructured my project and now the data isn't read anymore.
fs.watchFile("???", (curr, prev) => {
console.log("Ă„nderung auf Data.json");
fs.readFile("Data.json", "utf8", (err, data) => {
widgets = JSON.parse(data);
console.log("Daten ausgelesen" );
io.emit("dataUpdate", {widgets});
});
});
You can see my file paths here. The method above is in client.js and I want to refer to Data.json.
I tried:
"../Data.json" and
"/Server/Data.json"
Thanks for your help!
PS.: I know that there are threads explaining relative paths, but I still couldn't fix my problem.
You can use __dirname https://nodejs.org/docs/latest/api/modules.html#modules_dirname
example:
const path = require('path');
const filePath = path.join(__dirname, '..', 'data.json');

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