NodeJS fs并要求在不同的地方看
我试图循环通过一个目录,并要求在其中的每个文件。 我的代码正在工作,但我想知道为什么我不得不在fs函数中修改path。 (下面的代码剥离了无用的信息)
文件夹结构:
project |-- bin | `-- start |-- modules | |-- file1.js | `-- file2.js `-- package.json
/斌/启动:
#!/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" }
require
是一个Nodefunction。 只是在parsing相对path时require
使用__dirname
作为基本名称,而不是当前的工作目录,这也是process.cwd()
的结果。
在将它们传递给fs
函数之前,只需将__dirname
连接到相对path即可。 使用path.join(__dirname, '../modules')
和path.join(__dirname, '../modules', file)
。 在你的fs.readdir
和fs.stat
调用中使用这些:
fs.readdir(path.join(__dirname, '../modules'), function (err, files) { fs.stat(path.join(__dirname, '../modules', file), function (err, stat) {
这使得你的FS调用和需求alignment,以便加载正确的文件。
反过来也不难,要求加载任何path:
(而不是require(path.join('../modules/', file))
:
require(path.join(process.cwd(), '../modules/', file))
这是有效的,因为require
通过预先__dirname
而不改变绝对path,就像相对path__dirname
。
这背后的原因是require('../modules/' + file)
不是一个节点函数,它是common.js语法。 当你运行require
,它会看到文件相对于运行require
函数的文件,而当你运行fs
模块时,它会执行相对于node命令。