我如何在没有路径问题的情况下从其他目录中需要另一个模块?
例如,
src/index.js
,具有 require('../其他/main')
语句
哦,有错误,因为在 main.js.js < /code> js文件,有些东西要从路径中获取文件,这只是一个路径问题。 (例如 ./ somefile
显然在该其他
目录路径时将无法工作),
但是,如果我单独使用CLI,则将其单独使用,请 cd其他
和 npm start
(或 node main.js
),没有路径问题。
我如何需要
而无需 cd
进入目录才能使路径起作用?
但是我不明白,我如何很容易地需要一个JS文件,而是从带有包装的另一个目录。
How do I require another module from a different directory without having path issues?
For example,
src/index.js
, has a require('../other/main')
statement
Oh, there's an error, because in the main.js
JS file, there are things like getting files from paths, and it's just a path issue. (e.g. ./SOMEFILE
won't work when it's clearly in that other
directory path)
But, if I individually on my CLI, to cd other
, and npm start
(or node main.js
), no path issue.
How do I require
without having to cd
into the directory to make the path work?
But I don't get it, how do I just easily require a JS file but from another directory with a package.json or whatever?
发布评论
评论(1)
只需使用
process.chdir(Directory)
就没有路径问题。 httpps://nodejs.org/api/process.htmlpprocess.html#processchdml#processchdirdirrectory您可以使用
child_process.fork
为您的外部JS脚本的新过程(因此运行)。我们必须使用
process.chdir
,我找不到其他方法。Just use
process.chdir(directory)
so you don't have path issues. https://nodejs.org/api/process.html#processchdirdirectoryYou can use
child_process.fork
to make a new process of your external JS script (so it runs).https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options
We would have to use
process.chdir
, I cannot find another way.