【发布时间】:2016-11-26 09:30:08
【问题描述】:
我正在尝试遍历一个目录并要求其中的每个文件。我的代码正在运行,但我想知道为什么我必须修改 fs 函数中的路径。 (下面的代码去掉了无用的信息)
文件夹结构:
project
|-- bin
| `-- start
|-- modules
| |-- file1.js
| `-- file2.js
`-- package.json
/bin/start:
#!/usr/bin/env node
// Require dependencies
var fs = require('fs')
// Get modules
// NOTE: fs is looking in the project folder, but this file is in the bin folder
fs.readdir('./modules', function (err, files) {
// Handle error
if (err) {
console.log(err)
process.exit(1)
}
// Loop through files
files.forEach(function (file, index) {
// Get info about file
fs.stat('./modules/' + file, function (err, stat) {
// Handle error
if (err) {
console.log(err)
process.exit(1)
}
// If it is a file
if (stat.isFile()) {
// NOTE: require is looking in the bin folder, and this file is in the bin folder
require('../modules/' + file)
}
})
})
})
package.json:
{
"name": "modular-chat",
"version": "1.0.0",
"description": "A simple modular example of a chat application",
"scripts": {
"start": "node ./bin/start"
},
"author": "JoshyRobot",
"license": "MIT"
}
【问题讨论】:
-
观察力不错。
标签: javascript node.js require fs