node.js 从目录节点 Js 中检索文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7401340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:34:26  来源:igfitidea点击:

Retrieving files from Directory Node Js

node.js

提问by Sharmaji

I am using readDirSync to get the files from a Diretory. PLease find the code and error as following.

我正在使用 readDirSync 从目录中获取文件。请找到代码和错误如下。

var fs = require('fs');
var files = fs.readdirSync('./application/models/');
for(var i in files) {
  var definition = require('../application/models/'+files[i]).Model;
  console.log('Model Loaded: ' + files[i]);
}

I am getting error for line number 2 . ENOENT, No such file or directory './application/models/' at Object.readdirSync (fs.js:376:18)

我收到第 2 行的错误。ENOENT,在 Object.readdirSync (fs.js:376:18) 中没有这样的文件或目录“./application/models/”

I have application/models on the same dir. I already checked for '/application/models/' and 'application/models/' but failed. I can see the same thing running on server.

我在同一个目录上有应用程序/模型。我已经检查了 '/application/models/' 和 'application/models/' 但失败了。我可以看到同样的事情在服务器上运行。

Please help

请帮忙

Thanks

谢谢

回答by ivan ltheitroade

If you are using relative path when calling readdirSync, make sure it is relative to process.cwd(). However, "require" should be relative to the current script.

如果您在调用时使用相对路径readdirSync,请确保它是相对于process.cwd(). 但是,“require”应该是相对于当前脚本的。

For example, given the following structure

例如,给定以下结构

server.js (node process)
/lib/importer.js (the current script)
/lib/application/models/

you may need to write importer.jsas:

您可能需要将importer.js编写为:

var fs = require('fs');
var files = fs.readdirSync('./lib/application/models/');
for (var i in files) {
  var definition = require('./application/models/' + files[i]).Model;
  console.log('Model Loaded: ' + files[i]);
}

回答by Van Coding

Have you tried the following?

您是否尝试过以下方法?

var files = fs.readdirSync(__dirname+'/application/models/');