cbdeveloper
cbdeveloper

Reputation: 31335

Relative path error while executing Node script from another folder

I have this script that I need to run with node through the CLI.

And this script has a file relative file reference as:

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

The the file structure is like this:

> buildScripts
    myScript.js
> functions
    index.js

When I'm inside the buildScripts folder (on terminal) everything works:

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

But when I'm inside the MyProjectRoot folder, it throws:

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

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


QUESTION

How can I run this from myProject root folder and still get the correct path?


I don't know if it depends on the script / packages that I'm running, so here's the full source code for the script:

myScript.js

I'm using the replace-in-file package to update some imports. This will be a postBuild script at some point.

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

Upvotes: 2

Views: 454

Answers (1)

cbdeveloper
cbdeveloper

Reputation: 31335

The following question (link below) helped a lot (it's not a duplicate, though):

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

And here is the working version of the script. It works no matter where you execute it from.

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

Upvotes: 1

Related Questions