【问题标题】:JSON data returns {} without any dataJSON 数据返回没有任何数据的 {}
【发布时间】:2014-03-21 00:18:39
【问题描述】:
var getfiles = function (context) {

  var scriptPath = '/var/names/myfolder';
  fs.readdir(scriptPath, function (err, files) {
    if (err) return context.sendJson(err, 404);
    var resultingJson = {};
    for (var j = 0; j < files.length; j++) {
      subfolder = scriptPath + files[j];
      console.log(files[j]);// prints art,creation
      fs.readdir(subfolder, function (err, fi) {

                //fi prints [artdetails.txt,artinfo.txt]
                        // [creationdetails.txt,create.txt]    
          //  console.log(files[j]);// prints undefined here

        resultingJson[files[j]] = fi;

      });

    }
    console.log(resultingJson); // returing {}

    context.sendJson(resultingJson, 200);
  });
}

以上代码用于获取子文件夹 myfolder 中的文件,它包含 art,creation 并且在此艺术文件夹中包含文件 artdetails.txt,artinfo.txt 创建文件夹包含文件 creationdetails.txt,create.txt 等。

文件夹和文件已成功获取,但我想生成JSON 格式,如下所示:

{`art':['artdetails',artinfo],'creation':['creationdetails','create']} format

这怎么可能?

我使用了resultingJson[files[j]] = fi;,但它返回{}.

我的代码有什么问题?

【问题讨论】:

  • readdir异步。在读取目录之前,您正在调用 context.sendJson(resultingJson, 200);。解释和解决方法请看How to return the response from an AJAX call?(即使是关于Ajax,概念都是一样的)。
  • 我阅读了这篇文章,但我不知道我的代码做了什么更改?我该如何更改?

标签: jquery json node.js


【解决方案1】:

您关心在递归函数中将 resultsJson 的值重置为 {}。

试试这个代码

var getfiles = function (context) {

  var scriptPath = '/var/names/myfolder';
  var resultingJson = {};
  fs.readdir(scriptPath, function (err, files) {
    if (err) return context.sendJson(err, 404);
    for (var j = 0; j < files.length; j++) {
      subfolder = scriptPath + files[j];
      console.log(files[j]);// prints art,creation
      fs.readdir(subfolder, function (err, fi) {

                //fi prints [artdetails.txt,artinfo.txt]
                        // [creationdetails.txt,create.txt]    
          //  console.log(files[j]);// prints undefined here

        resultingJson[files[j]] = fi;

      });

    }
    console.log(resultingJson); // returing {}

    context.sendJson(resultingJson, 200);
  });
}

【讨论】:

  • 您在控制台上看到了多少次 console.log 打印?
【解决方案2】:

这里有一些问题。首先,Felix Kling 正确观察到 readdir 是异步的,更具体地说,是指 for 循环中的内部 readdir。您所看到的部分内容是您的 console.log 和 JSON 响应是在目录读取完成之前发生的。同样可能发生的是j 的上下文正在丢失,很可能是最后一个值。

async 之类的控制流库可能会有所帮助,例如 each 方法。

var fs = require('fs'),
    async = require('async');

var scriptPath = '/var/names/myfolder';

var getfiles = function(context) {
  // Read contents of the parent directory
  fs.readdir(scriptPath, function(err, files) {
    if (err) return context.sendJson(err, 404);
    var result = {};
    // Asynchronously iterate over the directories
    async.each(files, function iterator(directory, next){
      var subfolder = scriptPath + directory;
      // Read contents of the child directory
      fs.readdir(subfolder, function(err, file){
        if (err) return next(err);
        // Set the property
        result[directory] = file;
        // Now that we've finished reading these contents,
        // lets read the contents of the next child folder
        next();
        // When there are none left, the `complete` callback will
        // be reached and then it is safe to return a JSON string
      });
    }, function complete(err){
      // All children directories have been read
      // and the `result` object should be what we expect
      if (err) return context.sendJson(err, 404);
      context.sendJson(result, 200);
    });
  });
};

我已经通过模拟您的文件夹/文件结构对此进行了测试,它似乎可以正常工作。它生成了以下 JSON 字符串:

{"art":["artdetails.txt","artinfo.txt"],"creation":["create.txt","creationdetails.txt"]}

迭代器是并行调用的,因此顺序可能会切换,但应该不会产生影响。

【讨论】:

  • 我的荣幸。异步模块有一套很棒的工具,当你有时间的时候一定要看看其他方法。
  • 你好,我也有一个疑问
  • 这是使用`var file = fs.readdirSync(files);`的好方法吗
  • 这也可以。我通常会尽量避免同步。
【解决方案3】:

请尝试其他方式:

fs.readdir(scriptPath, function (err, files) {
    if (err) return context.sendJson(err, 404);
    files.forEach(function(file) {
      subfolder = scriptPath + file;
      console.log(file);
      fs.readdir(subfolder, function (err, fi) {
        resultingJson[file] = fi;
      });

    }
console.log(resultingJson);
context.sendJson(resultingJson, 200);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多