0

I'm trying to correctly configure my Gulp setup, and I want to load moduleA if it exists, or moduleB instead, if moduleA doesn't exists.

Trying to use this answer to check if a file exists, here is my code:

const fs = require('fs');

const moduleA = './moduleA.js';
const moduleB = './moduleB.js';

const myModule = require( (fs.existsSync(moduleA)) ? moduleA : moduleB );

But it is not working, my tasks always get the code from './moduleB.js' even if './moduleA.js' exists and is readable.

How can I modify this code to make it work, and require the correct module given the conditions?


Edit: I've tried the following code

const fs = require('fs');

const itexists = true;
const moduleA = './moduleA.js';
const moduleB = './moduleB.js';

const myModule = require( (itexists === true) ? moduleA : moduleB );

and it gives me values from moduleA (of course without checking its existence), so I can at least assume that the syntax is correct and that the problem lies with fs.existsSync().

For what I have understood, fs.existsSync() is supposed to give true or false as output, but apparently it is not working like that.

Sekhemty
  • 1,222
  • 2
  • 13
  • 33
  • Does this answer your question? [Node.js - check if module is installed without actually requiring it](https://stackoverflow.com/questions/15302618/node-js-check-if-module-is-installed-without-actually-requiring-it) – David784 Jan 09 '20 at 21:15
  • No, even with `try ... catch` it does not work as expected. – Sekhemty Jan 09 '20 at 21:24
  • I believe `require` follows different rules than the `fs` module as far as the current working directory. Maybe try something like this `fs.existsSync(path.join(__dirname, moduleA))`, and see if it works for you? – David784 Jan 09 '20 at 21:44
  • Using the path method seems to do the job, I'll test this more extensively as soon as possible. Meanwhile, if you want to put this in a proper answer, I can upvote and accept it. Thank you! – Sekhemty Jan 09 '20 at 22:19

0 Answers0