Node JS 'NODE_CONFIG_DIR' not overridden on startup using babel - node.js

I'm trying to organize some code from other developers.
The node js application is using es6 coding style and use babel to transpile the code.
when I want to implement the npm config package and set NODE_CONFIG_DIR to a specific folder the config folder is not overridden.
// THIS THING WORKS PERFECTLY !!!
const path = require("path");
process.env["NODE_CONFIG_DIR"] = path.join(__dirname, "src", "env");
require("#babel/register");
require("core-js/stable");
require("regenerator-runtime/runtime");
require("./src/game");
So when I run command 'nodemon app.js' -> the output is correct
But when I tried to transfer the code inside "./src/game/index.js"
The config directory points to the default directory which is config
src/game/index.js
const path = require("path");
process.env["NODE_CONFIG_DIR"] = path.join(__dirname, "env");
import express from "express";
So when I run command 'nodemon app.js' -> the output of NODE_CONFIG_DIR = /config
I want to put the process.env["NODE_CONFIG_DIR"] = path.join(__dirname, "env") on the src/game/index.js -> since later on this will be the entry point when I will compile the whole application source code

Related

How to combine multiple node js file into a single bundle using webpack

I am trying to create a single bundle from multiple javascript file in a nodejs application.
The configuration I am using looks somewhat like this:
const path = require('path')
const nodeExternals = require('webpack-node-externals')
'use strict';
module.exports = {
externals: [nodeExternals({})],
entry: './lib/index.js',
output: {
iife: false,
path: path.resolve(__dirname, 'lib'),
filename: 'bundle.js', // <-- Important
},
target: 'node', // <-- Important
};
The problem is when I run bundle.js command instead for it to do what the command says, i get the full source of the file streamed into the terminal.
It seems the file contains some sort of IIFE that gets executed immediately. I set iife: false to false in the webpack configuration but that also did not make any difference.
Any ideas what could be wrong?
Edit:
I am calling webpack by adding:
bundle: webpack --config webpack.config.js to script section in package.json and then I run npm run bundle
As an alternative, you could use https://www.npmjs.com/package/#vercel/ncc package to bundle all your Node.js code into one file.

Why we use path.join and not use relative path to access public directory in express and node server running?

I don't get it, why we don't use relative path in our app instead of this path that we get after path.join. is it not possible to use relative path like express.static('../public')?
const express = require('express');
const path = require('path');
const app = express();
const publicDir = path.join(__dirname,'../public')
app.use(express.static(publicDir));`
If you use a relative path with express.static(), then it's relative to where you launched your app, not necessarily relative to __dirname which means that merely changing the directory from where you launch your app from could break your app.
If you build a full path using __dirname, then this aspect of your app won't break if you happen to launch your app from a different directory. This is just more robust. If you intend for the path to be relative to __dirname, then you may as well enforce that in your code.

How to create a config file for node pkg

I use node pkg to create a .exe of my nodejs service: https://www.npmjs.com/package/pkg
My question is: how do I make the .exe use a config.js for some setup values? Basic stuff like ip, port, database name etc. Because I have 3 environments, and I would like to use the same exe for all, but different config.js files for each.
So far, if I do pkg app.js then it creates an .exe that doesn't look at any other files. Totally stand alone. How do I make it look at config.js when it is started up?
On the website they do have a section on config https://github.com/zeit/pkg#config but I do not understand how to make use of it. At the moment I have my app.js, and I have secrets.js which holds the config information.
I am not sure this is right way, but I hope this can be helpful to somebody.
Refer to pkg document, on the run time, __dirname becomes "/snapshot/project".
So, by checking __dirname, you can identify in which environment you are.
(node app.js or app.exe).
Then we can separate require sentence like below.
const PKG_TOP_DIR = 'snapshot';
const runInPKG = (function(){
const pathParsed = path.parse(__dirname);
const root = pathParsed.root;
const dir = pathParsed.dir;
const firstDepth = path.relative(root, dir).split(path.sep)[0];
return (firstDepth === PKG_TOP_DIR)
})();
let config = require('./appconfig.json');
if(runInPKG) {
const deployPath = path.dirname(process.execPath);
config = require(path.join(deployPath, 'appconfig.json'));
}
Adding above code to your app.js makes some warning when pkg build.
pkg . --targets node8-win-x64 --out-path ./dist
pkg#4.4.0
Warning Cannot resolve 'path.join(deployPath, 'appconfig.json')'
app.js
Dynamic require may fail at run time, because the requested file
is unknown at compilation time and not included into executable.
Use a string literal as an argument for 'require', or leave it
as is and specify the resolved file name in 'scripts' option.
https://github.com/vercel/pkg/issues/195
use fs to read config file insead of require or import
eg:
const configPath = path.join(process.cwd(), './config/config.json');
lset data = fs.readFileSync(configPath);
same question link:excluding config file while converting node js files to exe using pkg

How to get the root of project which installed my npm module?

I am developing an NPM package. Now I want to know the easiest way to get the root of the project which utilizes my custom package.
Within my package itself it is pretty easy to get the root in node.js like so:
__dirname
This points to the root of my package itself though. I would like to get the root of the project which actually performed the npm install of my package though.
Obviously, I could simply go up from the node_modules directory and assume that the root directory is there but this sounds really bad.
Is there a standard way to achieve this?
you could use app-root-path which is an npm module and its pretty neat.
npm i -S app-root-path
after that just do
var reqlib = require('app-root-path').require;
var myModule = reqlib('/lib/my-module.js');
You can use the info from: require.main
The Module object representing the entry script loaded when the
Node.js process launched. See "Accessing the main module".
const path = require('path');
console.log(path.dirname(require.main.filename));
Having this folder structure:
/app
entry.js
node_modules/
my-package/
index.js
app/entry.js
const myPackage = require('my-package');
app/node_modules/my-package/index.js
const path = require('path');
console.log(path.dirname(require.main.filename));
And when you call: node entry.js
You will get: /app printed to stdout.
KISS
const fullPath = path.dirname(require.main.filename);
const regexResp = /^(.*?)node_modules/.exec(fullPath);
const appRoot = regexResp ? regexResp[1] : fullPath;
console.log(appRoot); // outputs the directory which is the root of this project

How get path to folder "node_modules" in js file?

Node.js - 8.2.1
I my index.js I hard code path to node_modules:
'use strict';
var NPM_NODE_MODULES_BASE_DIR = 'd:\\Programs\\nodejs\\node_modules\\npm\\node_modules\\'
var express = require(NPM_NODE_MODULES_BASE_DIR + '\express'),
bodyParser = require(NPM_NODE_MODULES_BASE_DIR +'body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
But it's not very good, because code is not portable. How I can get path to folder node_modules of Node.js ?
Instead of installing npm modules globally you could install them in your src folder, whenever you are in the src folder and do an npm install it should be installed in the local npm modules folder in the src file making it portable, you could use --save to add it to your dependencies so you can get it while initialising your node project
Here is an excerpt from the nodejs current master branch source documentation [doc/api/modules.md]...
...high-level algorithm in pseudocode of what require.resolve() does:
require(X) from module at path Y
If X is a core module,
a. return the core module
b. STOP
If X begins with '/'
a. set Y to be the filesystem root
If X begins with './' or '/' or '../'
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
LOAD_NODE_MODULES(X, dirname(Y))
THROW "not found"
Please note that you can have more than one node_modules (see https://docs.npmjs.com/files/folders).
Most of the times, the node_modules you want is the parent path of the directory your current module lives in:
const path = require('path').resolve(__dirname, '..');

Resources