【问题标题】:Creating An Object From A Directory从目录创建对象
【发布时间】:2020-06-04 09:02:10
【问题描述】:

我只是想知道如何使用节点 js 从目录创建 JavaScript 对象。

这就是我的意思: 如果根文件夹是“test”并且树看起来像this 所以对象结构看起来像这样:

{ test: { joe: {mama: "(file contents)"}, pp: {help: "very mature example\r\ni'm aware"} } }

编辑:这是我的尝试

const fs = require("fs");
const path = require("path");

const root = "test";
const dir = __dirname + "\\" + root + "\\";
var currentFolder = dir.replace(__dirname + "\\", "");

var data = {};

const getFileSize = function (dirPath) {
  files = fs.readdirSync(dirPath);

  var length = 0;

  files.forEach(function (file) {
    length++;
  });

  return length;
};

fs.readdirSync(dir).forEach((rootFile, rootIndex) => {
  fs.readdirSync(currentFolder).forEach((file, index) => {
    if (getFileSize(currentFolder) - 1 == index) {
      console.log(index, file, rootFile, currentFolder);
      currentFolder = currentFolder.replace(`\\file`, "");
      index++;
    }

    // if (file.includes("."))
    //   data[currentFolder + file] = fs.readFileSync(currentFolder + file, "utf8");
    // else currentFolder = currentFolder + file + "\\";
  });
});

console.log(data);

【问题讨论】:

标签: javascript node.js object npm


【解决方案1】:

是的,经过数小时的谷歌搜索和堆栈溢出,我发现了这个:

    var fs = require("fs");
var path = require("path");
var walk = function (dir, done) {
  var results = [];
  fs.readdir(dir, function (err, list) {
    if (err) return done(err);
    var i = 0;
    (function next() {
      var file = list[i++];
      if (!file) return done(null, results);
      file = path.resolve(dir, file);
      fs.stat(file, function (err, stat) {
        if (stat && stat.isDirectory()) {
          walk(file, function (err, res) {
            results = results.concat(res);
            next();
          });
        } else {
          results.push(file);
          next();
        }
      });
    })();
  });
};

var root = "test";
var data = {};

walk("test", function (err, results) {
  if (err) throw err;

  for (i in results) {
    data[
      results[i].replace(__dirname + "\\" + root + "\\", "")
    ] = fs.readFileSync(results[i], "utf8");
  }

  console.log(data);
});

【讨论】:

    猜你喜欢
    • 2020-11-01
    • 1970-01-01
    • 2022-08-04
    • 1970-01-01
    • 2022-01-10
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    相关资源
    最近更新 更多