Thursday, 18 April 2019

Question of specifying path of file module

Hi. There is a question stuck in my head for years and I am too afraid to ask because it sounds so stupid, but I keep thinking about it while I cannot come up with a good answer. I hope someone can convince me or point out what is wrong in my question.Imagine a simple Node.js application with the following project layout:├───index.js │ ├───engines | ├───layout-engine.js │ └───render-engine.js │ ├───filters │ ├───request-filter.js │ └───response-filter.js │ └───helpers └───auth-helper.js Now index.js has to make use of engines/layout-engine.js and engines/render-engine.js.According to the Node.js documentation, one can simply do (in index.js):const layoutEngine = require('./engines/layout-engine.js'); const renderEngine = require('./engines/render-engine.js');However, the path separator on Windows (\) is different from that on Linux and UNIX (/), so is it better (or "correct") to do it in the following way?``` const path = require('path');const layoutEngine = require(path.join( __dirname, 'engines', 'layout-engine.js' )); const renderEngine = require(path.join( __dirname, 'engines', 'render-engine.js' )); ```Now imagine filters/request-filter.js has to make use of helpers/auth-helper.js. In filters/request-filter.js, instead of:const authHelper = require('../helpers/auth-helper.js');I would do:``` const path = require('path');const authHelper = require(path.join( __dirname, '..', 'helpers', 'auth-helper.js' )); ```Is it just me being crazy here and I should not worry too much about the path separator?Bonus question: Imagine an application is so complex that many file modules have to "import" several other file modules, and one day you want to move or rename several file modules. How do you do such refactoring and make sure that the paths specified in the file modules are updated?Edit: Added a bonus question.

Submitted April 18, 2019 at 04:25PM by B45tFYE6Em

No comments:

Post a Comment