Issue
I'm making an electron app (html/css/js/nodejs) and I'm doing pretty good right now,so I wanted to create a 'Tree file manager' which is an important feature in most of the concept of my app's type. I want to be able to create delete, move, and, rename folders and content in that folders I do not want a modern file manager but at least a functional one. I have been searching for days for now and nothing. Please link resources or explain how can I achieve that.
Solution
Electron comes with Node.js which has powerful file system APIs that you can use for all the functionality of your file manager.
I wrote a few functions to help you get started:
- The
getDirItemInfo()
function creates a data object for the specified path - The
getDirItems()
function gets the contents of a directory and creates a data object for each item.
const _path = require('path')
const fs = require('fs')
async function getDirItemInfo (path) {
const basePath = _path.parse(path).base
return await fetchItemObject(path, basePath)
}
async function getDirItems (dirPath) {
return new Promise((resolve, reject) => {
// Read directory and get items
fs.promises.readdir(dirPath)
.then(basePaths => {
const statsPromises = basePaths.map(basePath => {
const path = _path.join(dirPath, basePath)
return fetchItemObject(path, basePath)
})
return Promise.all(statsPromises)
})
.then(contents => {
// Remove items that couldn't be accessed (undefined, null, false)
contents = contents
.filter(Boolean)
resolve(contents)
})
.catch((error) => {
console.log(error)
})
})
}
async function fetchItemObject (path, basePath) {
try {
let dirItemCount = null
const stat = await fs.promises.lstat(path)
const name = basePath === '' ? path : basePath
if (stat.isDirectory()) {
// Count dir items and ignore dirs that couldn't be accessed by readdir
try {
const dirItems = await fs.promises.readdir(path)
dirItemCount = dirItems.length
}
catch (error) {
console.log(error)
}
stat.size = null
}
return ({
dirItemCount,
name,
path,
stat
})
}
catch (error) { console.log(error) }
}
// USE FUNCTIONS:
let path1 = _path.normalize('E:/test/test.jpg')
let path2 = _path.normalize('E:/test')
fetchItemObject(path1)
.then((result) => {
console.log(result)
})
getDirItems(path2)
.then((result) => {
console.log(result)
})
You can find all Node.js file system APIs in their documentation:
https://nodejs.org/api/fs.html
Answered By - AlekseyHoffman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.