javascript - 从另一个文件夹执行 Node 脚本时出现相对路径错误

标签 javascript node.js path

我有这个脚本,需要通过 CLI 使用 node 运行。

并且此脚本有一个文件相关文件引用为:

files: '../functions/index.js',

文件结构是这样的:

> buildScripts
    myScript.js
> functions
    index.js

当我在 buildScripts 文件夹中(在终端上)时,一切正常:

>> C:\MyProjectRoot\buildScripts> Node myScript.js

但是当我在 MyProjectRoot 文件夹中时,它会抛出:

>> C:\MyProjectRoot> node buildScripts/myScript.js

Error occurred: Error: No files match the pattern: ../functions/index.js


问题

如何从 myProject 根文件夹运行它并仍然获得正确的路径?


我不知道它是否取决于我正在运行的脚本/包,所以这里是脚本的完整源代码:

myScript.js

我正在使用 replace-in-file 包来更新一些导入。在某些时候,这将是一个 postBuild 脚本。

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);
  })
;

最佳答案

以下问题(下面的链接)帮助很大(虽然它不是重复的):

What is the difference between __dirname and ./ in node.js?

这是脚本的工作版本。无论您从何处执行它,它都能正常工作。

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);
  })
;

关于javascript - 从另一个文件夹执行 Node 脚本时出现相对路径错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58713905/

相关文章:

go - Go语言如何指定 `template.ParseFiles`的文件位置?

node.js - 将 gsap Node 模块与 Meteor 一起使用

javascript - 使用 ShouldJS 比较来自 Mongoose 的数组

javascript - 在 Handlebars.js 中的新行上打印输出

wordpress - curl 错误 77 : error setting certificate verify locations

javascript - 如何在 GWTTestCase 中测试 "Timer code"?

javascript - PHP - 将图像插入数据库

javascript - Photoshop 脚本 - 更改特定文本图层内容

javascript - html 页面中的 Jquery 脚本不起作用

javascript - 使用 svg map 激活类