Javascript 从其他文件夹执行节点脚本时出现相对路径错误
我有这个脚本,需要通过CLI与Javascript 从其他文件夹执行节点脚本时出现相对路径错误,javascript,node.js,path,Javascript,Node.js,Path,我有这个脚本,需要通过CLI与节点一起运行 此脚本具有一个文件相对文件引用,如下所示: files: '../functions/index.js', 文件结构如下所示: > buildScripts myScript.js > functions index.js 当我在buildScripts文件夹(在终端上)中时,一切正常: >C:\MyProjectRoot\buildScripts>node myScript.js 但是当我在MyProjectRoot文
节点一起运行
此脚本具有一个文件相对文件引用,如下所示:
files: '../functions/index.js',
文件结构如下所示:
> buildScripts
myScript.js
> functions
index.js
当我在buildScripts
文件夹(在终端上)中时,一切正常:
>C:\MyProjectRoot\buildScripts>node myScript.js
但是当我在MyProjectRoot
文件夹中时,它抛出:
>C:\MyProjectRoot>node buildScripts/myScript.js
发生错误:错误:没有与模式匹配的文件:../functions/index.js
问题
如何从myProject
根文件夹运行此文件,并仍然获得正确的路径
我不知道这是否取决于我正在运行的脚本/包,因此下面是脚本的完整源代码:
myScript.js
我正在使用replace-in-file
包更新一些导入。在某个时候,这将是一个后期构建脚本
const escapeStringRegexp = require('escape-string-regexp');
const fromPath = './src';
const fromPathRegExp = new RegExp(escapeStringRegexp(fromPath),'g');
const replace = require('replace-in-file');
const options = {
files: '../functions/index.js', // <----------------------------------
from: fromPathRegExp,
to: './distFunctions',
};
replace(options)
.then(results => {
console.log('Replacement results:', results);
})
.catch(error => {
console.error('Error occurred:', error);
})
;
const escapeStringRegexp=require('escape-string-regexp');
常量fromPath='./src';
const fromPathRegExp=new RegExp(escapeStringRegexp(fromPath),'g');
const replace=require('replace-in-file');
常量选项={
文件:'../functions/index.js',//{
console.log('替换结果:',结果);
})
.catch(错误=>{
console.error('发生错误:',错误);
})
;
下面的问题(下面的链接)帮助很大(尽管它不是重复的):
这是脚本的工作版本。无论从何处执行,它都可以工作
const path = require('path');
const escapeStringRegexp = require('escape-string-regexp');
const fromPath = './src';
const fromPathRegExp = new RegExp(escapeStringRegexp(fromPath),'g');
const replace = require('replace-in-file');
const options = {
files: '../functions/index.js',
from: fromPathRegExp,
to: './distFunctions',
};
console.log('This is the __dirname: ' + __dirname);
console.log('This is the __filename: ' + __filename);
console.log('This is process.cwd(): ' + process.cwd());
console.log('This is the ../functions/index.js: ' + path.resolve('../functions/index.js'));
process.chdir(__dirname);
console.log('CHANGED cwd WITH process.chdir');
console.log('This is the __dirname: ' + __dirname);
console.log('This is the __filename: ' + __filename);
console.log('This is process.cwd(): ' + process.cwd());
console.log('This is the ../functions/index.js: ' + path.resolve('../functions/index.js'));
replace(options)
.then(results => {
console.log('Replacement results:', results);
})
.catch(error => {
console.error('Error occurred:', error);
})
;
您可以使用\uuuu dirname
或\uuu filename
来使用path
模块构建您的相对路径。请参见。我更改了cwd
(这是'../someDir'
符号的基础(除require之外)。因此,相对路径现在可以工作。我使用process.chdir(\uu dirname)更改了它;