簡體   English   中英

單擊根文件夾數組中的任何元素並獲取其路徑?

[英]Click any element in array of root folder and get its path?

我正在嘗試從應用程序的根文件夾數組中獲取當前單擊的文件夾,並使用readdirSync進行讀取,但找不到任何有用的信息。

到目前為止,我得到的只是單擊時的索引號,但由於它不是字符串,所以無法讀取。

這是我現在所擁有的:

const fs = require('fs');

$('li').click(function() {

    file = $('li').index(this);
    fs.readdirSync(file);
    console.log(file);

})

我的應用程式

我的應用

因此,要讀取我的根文件夾,我需要: let files = fs.readdirSync('.')和一個forEach函數。 例如,我想單擊“ js”文件夾,並顯示其中的內容,但我不知道如何。

我是電子和node.js的新手:)

謝謝!

此代碼段將在下面的代碼中使用:

  const fileSystem = require("fs");
  const getDirectoryContents = path => fileSystem.readdirSync(path);

假設您的ul有一個名為main的ID,這就是我要做的:

$("#main li").on("click", function clickHandler() {
    const $clickedElement = $(this);
    const elementName = $clickedElement.text(); // gets the text that was clicked
    const fsEntry = fileSystem.statSync(elementName);
    if (fsEntry.isDirectory()) { // retrieve the contents only if the clicked text represents a folder
      const files = ['<ul>'].concat(
        getDirectoryContents(elementName).map(entryName => `<li>${entryName}</li>`),
        '</ul>'
      ).join('');
      $clickedElement.append(files); // not exactly the best way to do it, but does the job
    } else {
      // do something if the entry is a file
    }
  });

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM