How can I pass process.env from main to my npm package - node.js

In my npm package I want to access process.env.MYCUSTOMVAR, which is from main.app. When I try to print process.env.MYCUSTOMVAR in the package, it returns {}. How can I access this variable?
In case it is relevant: my npm package has built using babel from webpack build.

Consider instead exporting that object in main.app and accessing it from external scripts using the require syntax:
// main.app.js
// ...whatever code you have...
module.exports.MYCUSTOMVAR = process.env.MYCUSTOMVAR;
// your_package.js
var MYCUSTOMVAR = require("./main.app").MYCUSTOMVAR;
That should work!

Related

Node.js Dependencies as Singletons

I am trying to create my own npm package my-package that relies on a dependency dependency-a and is used in some project cool-project that relies on both my-package and dependency-a.
cool-project
- dependency-a
- my-package
- dependency-a
dependency-a:
export const someVar = 0;
my-package:
import depA from 'dependency-a'
const someFun = () => {
depA.someVar = 1;
}
cool-project:
import depA from 'dependency-a';
import myPackage from 'my-package';
myPackage.someFun();
console.log(depA.someVar); // expected (desired) 1, actual 0
The above would work if myPackage was a module apart of cool-project, however since I want my-package to be a standalone npm module, when I try to link it in cool-project it seems to be relying on a separate version of dependency-a.
Is there a way to create an npm module that can modify a singleton of a third party library, and share that across two modules relying on it automagically. I am using babel/webpack to build my-package so if there is a way to do it through that, then that works for me too!
Side note: I know that I could do something like return depA from my-package--this is not workable for what I need to do. I'm trying to use a version of this example to create a connection middleware for a database.
Add dependency-a as a peer dependency in my-package's package.json file,
"peerDependencies": {
"dependency-a": "1.x"
}
Now, when installing my-package, dependency-a won't be installed automatically if there is another dependency-a (with same version you declared) installed in cool-project.

How to include dependencies in J2V8

How to include dependencies in J2V8? I would like to use certain dependencies in the javascript file for instance the crypto package.
var crypto = require('crypto');
function foo(){ return crypto.createHash('md5').update('Apple').digest("hex");}
However, I got the following error saying require keyword is undefined.
undefined:1: ReferenceError: require is not defined
var crypto = require('crypto');
^
ReferenceError: require is not defined at <anonymous>:1:14
com.eclipsesource.v8.V8ScriptExecutionException
at com.eclipsesource.v8.V8._executeVoidScript(Native Method)
Can anyone tell me how to import an package into J2V8?
Unless you're working with Node, require is not a feature. Usually, you want to use a bundler like webpack to pack your structured source code into one large file so that it can be understood by browsers. This way you can use require and npm packages for your frontend code, which makes development easier, and a bundler turns it with every build (or live update) into a different format, that's hard to read for humans, but is valid Javascript.
I have had success using node modules in J2v8, please check out this blog :http://eclipsesource.com/blogs/2016/07/20/running-node-js-on-the-jvm/
NodeJs nodeJS = NodeJs.createNodeJs();
After registering callbacks
nodeJs.exec(File thescripttoexecute)
Make sure you have the proper path to the node modules in the require() command.
You may have to make a nodejs package that takes dependencies and exports what you need. Then, You have to execute npm install manually.
or You can just npm install what-you-need.
Create Node JS Runtime, and use require with your your-package-dir/index.js or exact location of module that you need. like this:
V8Object module = nvm.require(file);
Now you can call the function likes:
module.executeJSFunction("test");
To deliver entire dependencies you have to bundlize module directory your self.
What if you have to support cross-platform, refer https://www.npmjs.com/package/node-pre-gyp also.

Do all npm packages need an export?

I am new to nodejs packages and what I understood was that to share code you had to do a module.export (in addition to adding a package.json)
For example bootstrap-select does not have an export function but is available on npm.
So my question is do all modules require an export and also can I do a require('bootstrap-select') in my code?
no, all npm modules do not require an export. npm is now being used more generally for not only javascript packages intended for use under node.js but front end code for browsers, CSS libraries, etc. At the very least, an npm package could just deliver a payload of files not even including any javascript, such as some images, some CSS, some HTML, etc.
So you can only do require('some-module') if that package has either an index.js file or has set the main property in it's package.json file properly.
However if you are authoring a javascript module for node.js, then yes you'll need to export something in order for your module to load properly.
No, npm modules do not require doing something with module.exports. If you do not touch that object, requireing your module will return an empty object (since that is the default for module.exports. However, this can be useful if your module is only intended to be required for side effects, rather than a return value.
For example, the module you linked to modifies global state by attaching a jQuery event handler.
As per i know ,
1.All npm modules are not required to build an app.
2.If we use var bootStrap = require('bootstrap-select'); using bootStrap variable you can access bootStrap module.
so we can pass that object in anywhere of your code
3.To install a dependency modules,
In package.json give dependency block as like this
"dependencies": {
"express": "2.3.12",
"jade": "latest",
"redis": "0.6.0"
}
you can change and edit your packages. then enter a command npm install in command prompt it will install only dependency modules.
If i made any mistakes please correct me Thanks.

Can I access locally-installed packages from a globally-installed package?

I don't know if I've worded the question properly, so I apologize if it isn't clear from the title what I mean.
Say I have an NPM package which installs an executable. Presumably I want users to install this package with the -g flag so that they can run it whenever.
In this case, when I call require() from within the executable, it will look for packages installed globally.
But suppose this package provides generic functionality for Node projects. I might want to know which packages the current project has installed locally. Should I just assume:
path.join(process.cwd(), 'node_modules')
Or is there a more "correct" way to set the NODE_PATH in this case? (Or rather than set NODE_PATH, should I just require(absolute_path_to_file)?)
require will not only lookup the package inside $(CWD)\node_modules but also inside all node_modules of parent, grandparent, etc. So you can use resolve on npm to solve this problem
FILE: your_global_command.js
// npm install resolve
var resolve = require('resolve').sync;
// Lookup for local module at current working dir
function require_cwd(name) {
var absolute_path = resolve(name, { basedir: process.cwd() });
return require(absolute_path);
}
// Load local express
// this will throw an error when express is not found as local module
var express = require_cwd('express');
I also create a package to require a package at current-working-dir (instead of __dirname of module):
https://npmjs.org/package/require-cwd

node js elementtree required get Cannot find module 'sax'

i am attempting to use elementtree in my node js server
however the following message is genearted on server startup
Cannot find module 'sax'
i had to install elementree from zip, what have i done wrong?
these are my rquire statements
var cache = require('./node_modules/node-cache');
var elementTree = require('./node_modules/node-elementtree');
this is my folder structure
module\node_modules\node-cache
module\node_modules\node-elementtree
my server js script resides in \module
The problem is because you are not using npm for installing your node-elementtree module
This is the package.json of node-elementtree. and it is clearly mentioned that there is a dependency on sax 0.3.5
"dependencies" : {
"sax": "0.3.5"
}
Incase if you had done npm install it would have resolved your dependency constraints.
Inside your node-elementtree module it uses sax here and your require didn't resolve to a proper module. Hence the error. Incase you can't use npm then install sax too using zip if possible but it may increase your dependency list once again as the above. So, Try resolving npm issue
Also you don't need to use
var cache = require('./node_modules/node-cache');
var elementTree = require('./node_modules/node-elementtree');
in your code
var cache = require('node-cache');
var elementTree = require('node-elementtree');
the above would do. Node automatically locates the module from ./node_modules directory and even from many more places

Resources