Node.js服务器读取文件的顺序?

发布于 2024-11-07 02:09:10 字数 259 浏览 0 评论 0原文

我的node.js应用

程序中有2个js文件文件a定义了全局对象foo

在文件b中我可以参考foo

但如果文件 b 在文件 a 之前加载,则会发生错误。

我正在使用节点的 fs 模块来读取文件。我使用 readdir,然后对每个文件使用 forEach require 。在我的系统上,文件总是按字母顺序读取,所以从来没有任何问题。

我可以依赖按字母顺序读取这些文件吗?

I have 2 js files in my node.js app

File a defines global object foo

In file b I can refer to foo.

But if file b is loaded before file a, then an error occurs.

I'm using node's fs module to read the files. I use readdir, and then forEach require on every file. On my system the files are always read alphabetically, so there is never any problem.

Can I depend on those files being read alphabetically?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

娇纵 2024-11-14 02:09:10

为了确定起见,您可以按名称对文件数组进行排序。

fs.readdir(path, function(err, files) {
    files.sort(function(a, b) {
        return a < b ? -1 : 1;
    }).forEach(function(file, key) {
        // stuff
    });
});

You can sort your array of files by name instead to be sure.

fs.readdir(path, function(err, files) {
    files.sort(function(a, b) {
        return a < b ? -1 : 1;
    }).forEach(function(file, key) {
        // stuff
    });
});
月光色 2024-11-14 02:09:10

因为您正在处理文件数组,所以最好的办法是对数组进行排序,然后对其进行处理;仅当前一个文件完成后才开始读取新文件。

Because you're working with an array of files, you best bet is to sort the array then work through it; Only starting a new file read when the previous one has completed.

溺渁∝ 2024-11-14 02:09:10

暂时忽略全局变量通常是一个坏主意的事实...:-)

如果您已经知道需要加载的文件路径,您可能希望使用如下结构:

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

/**
 * loads and evals two initialization files in order
 * @param {callback} onComplete  called on init completion
 * @param {callback} on Error    called on error (optional)
 * @return null
 */

function init_app(onComplete,onError){

  var first_filepath  = './file1.js',
      second_filepath = './file2.js';

  // read/eval first file
  fs.readFile(first_filepath,function(first_err,first_result){

    if (first_err) {
      if(onError) {
        onError(first_err.message);
        return;
      }
      else {
        throw first_err;
      }
    }

    // evaluate first result
    try {
      vm.createScript(first_result).runInThisContext();
    }
    catch (e) {
      err_msg='failed to eval source from first file:' + e.type;
      if(onError) {
        onError(err_msg);
        return;
      }
      else {
        throw err_msg;
      }
    }

    // check for existence of foo global
    if(foo == undefined) {
      var msg='foo is undefined after first file read';
      if(onError) {
        onError(err_msg);
        return;
      }
      else {
        throw err_msg;
      }
    }

    // read/eval second (dependent) file
    fs.readFile(second_filepath, function(second_err,second_result){

      if (second_err) {
        if(onError) {
          onError(second_err.message);
          return;
        }
        else {
          throw second_err;
        }
      }

      // evaluate second, dependent result
      try {
        vm.createScript(second_result).runInThisContext();
      }
      catch (e) {
        err_msg='failed to eval source from second file:' + e.type;
        if(onError) {
          onError(err_msg);
          return;
        }
        else {
          throw err_msg;
        }
      }

      // trigger callback
      if(onComplete) onComplete();

    }); // end fs.readFile(second_filepath,...

  }); // end fs.readFile(first_filepath,...

}; // end init_app()

用作:

var onComplete = function(){ console.log('init complete'); },
    onError    = function(msg){ console.error(msg); };

init_app(onComplete,onError);

然后再说一次,如果您只加载一旦在应用程序启动时使用这些文件,您应该使用 require()。

Ignoring for the moment the fact that global variables are usually a bad idea...:-)

If you already know the filepaths you need to load, you might wish to use a structure like:

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

/**
 * loads and evals two initialization files in order
 * @param {callback} onComplete  called on init completion
 * @param {callback} on Error    called on error (optional)
 * @return null
 */

function init_app(onComplete,onError){

  var first_filepath  = './file1.js',
      second_filepath = './file2.js';

  // read/eval first file
  fs.readFile(first_filepath,function(first_err,first_result){

    if (first_err) {
      if(onError) {
        onError(first_err.message);
        return;
      }
      else {
        throw first_err;
      }
    }

    // evaluate first result
    try {
      vm.createScript(first_result).runInThisContext();
    }
    catch (e) {
      err_msg='failed to eval source from first file:' + e.type;
      if(onError) {
        onError(err_msg);
        return;
      }
      else {
        throw err_msg;
      }
    }

    // check for existence of foo global
    if(foo == undefined) {
      var msg='foo is undefined after first file read';
      if(onError) {
        onError(err_msg);
        return;
      }
      else {
        throw err_msg;
      }
    }

    // read/eval second (dependent) file
    fs.readFile(second_filepath, function(second_err,second_result){

      if (second_err) {
        if(onError) {
          onError(second_err.message);
          return;
        }
        else {
          throw second_err;
        }
      }

      // evaluate second, dependent result
      try {
        vm.createScript(second_result).runInThisContext();
      }
      catch (e) {
        err_msg='failed to eval source from second file:' + e.type;
        if(onError) {
          onError(err_msg);
          return;
        }
        else {
          throw err_msg;
        }
      }

      // trigger callback
      if(onComplete) onComplete();

    }); // end fs.readFile(second_filepath,...

  }); // end fs.readFile(first_filepath,...

}; // end init_app()

Used as:

var onComplete = function(){ console.log('init complete'); },
    onError    = function(msg){ console.error(msg); };

init_app(onComplete,onError);

Then again, if you only load these files once at the start of your application, you should use require().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文