javascript - Process.chdir() 对 require 没有影响

标签 javascript node.js module commonjs working-directory

给定结构目录结构:

.
├── alpha.js
└── foo
    └── beta.js

和文件内容

alpha.js

module.exports = "alpha"

foo/beta.js

var cwd = process.cwd()
process.chdir('../')
var alpha = require('./alpha.js')
console.log(alpha)
process.chdir(cwd)

来自 foo/beta.js。我希望能够让 require 认为当前工作目录是项目根目录。运行以下命令时,上面的示例不起作用。

node ./foo/beta.js

但是,如果我将 foo/beta.js 中的代码切换到以下内容。从系统中读取文件并将其传递给 npm 模块 _eval .

更新了 foo/beta.js

var path = require('path')
var cwd = process.cwd()
process.chdir(path.join(__dirname, '..'))
var fs = require('fs')
var _eval = require('eval')
var alpha = _eval(fs.readFileSync('./alpha.js'))
console.log(alpha)
process.chdir(cwd)

这确实有效,这证明 require 也应该是可能的。无论您从哪里运行,它都将始终需要该文件。 node ./foo/beta.jscd foo && node ./beta.js

有什么方法可以在文件中添加或设置 require 使用的目录?

最佳答案

来自node.js doc for require() :

If the module identifier passed to require() is not a native module, and does not begin with '/', '../', or './', then node starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location.

If it is not found there, then it moves to the parent directory, and so on, until the root of the file system is reached.

由此可见,当前目录并没有被用于加载模块。这里的主要内容应该是模块路径是相对于当前模块的位置的。这允许模块以独立的方式加载子模块,而无需知道父模块在目录结构中的位置。

如果传递给它的文件名不是以路径分隔符或 . 开头,这里有一个变通函数,它从当前目录加载模块文件描述符。

var path = require('path');

function requireCWD(fname) {
    var fullname = fname;
    if (fname && fname.length && 
      !path.isAbsolute(fname) &&
      fname.charAt(0) !== '.') {
        fullname = path.join(process.cwd(), fname);
    }
    return require(fullname);
}

然后,您给 requireCWD 的任何文件名都不是相对的并且不以“.”开头。将相对于当前工作目录加载。如果你甚至想允许 "."".." 相对于当前工作目录,那么你可以删除 '.' 的测试。 来自函数。

关于javascript - Process.chdir() 对 require 没有影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31955383/

相关文章:

javascript - Vue.js 自定义指令不运行 componentUpdated Hook ?

javascript - jQuery 用户界面 : changing button text distorts button sizing

module - 更改 Dotnetnuke 中特定页面的外观

class - NodeJS 模块与类

Ruby 嵌套模块作为命名空间

javascript - Ember 2,显示空模型的消息而不是在 hbs 模板中加载,每个或如果

javascript - scrollTop 动画后滚动将不起作用

Node.js - 将多个文件作为附件从服务器推送到客户端

css - 无法使用 Node-sass、bootstrap-sass 加载 Bootstrap

javascript - 使用 ngrok 的侧载应用程序无法正常工作