I've created 2 node packages namely secrets-lib and initializer-lib.
init method of the initializer-lib is used to initialize value of my-secret.
Now I want to use this my-secret in node-js code so I've installed both 'secrets-lib' and 'initializer-lib' and called init method,
When I am trying to console.log my-secret, getting undefined
Why is so ?., is this expected output ?
Related
I saw that best way to store some secret strings is using config package and environment variables. This is how I set it up.
Created a config folder with 2 files (default.json, custom-environment-variables.json)
In default.json I created this:
{
"passPrivateKey": ""
}
In custom-environment-variables.json I created this:
{
"passPrivateKey": "nodeProject_passPrivateKey"
}
After I set the variable in terminal with this command:
npm config set nodeProject_passPrivateKey=randomKey
When I am reading the variable from terminal with command below it works fine and shows the correct value
npm config get nodeProject_passPrivateKey
However in code I have these lines:
if (!config.get("nodeProject_passPrivateKey")) {
console.error("nodeProject_passPrivateKey has not been set");
}
So yeah the problem is this method config.get() is not reading the value and I am getting the error not set from above. I tried doing everything in vs code as admin, and using config.get on "nodeProject_passPrivateKey" and "passPrivateKey" but the method is still not reading any value.
Why not use dotenv?
You create an .env file where you store all your secrets and you access them through
process.env.myvar
I'm enthusiastic about Deno so I'm giving it a try. Found a tutorial on building a REST API here.
So, when I'm trying to run it, I get this InvalidData error:
error: Uncaught InvalidData: data did not match any variant of untagged enum ArgsEnum
at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11)
at Object.sendAsync ($deno$/ops/dispatch_json.ts:98:10)
at async Object.connect ($deno$/net.ts:216:11)
at async Connection.startup (https://deno.land/x/postgres/connection.ts:138:17)
at async Client.connect (https://deno.land/x/postgres/client.ts:14:5)
at async Database.connect (file:///Users/svenhaaf/git/deno/logrocket_deno_api/db/database.js:17:5)
Now, it looks to me that something is wrong when trying to connect to the database, but I can't really figure out what.
What does this InvalidData error mean? How should I fix this?
FYI my deno --version prints:
deno 0.42.0
v8 8.2.308
typescript 3.8.3
Code:
I cloned the repo from https://github.com/diogosouza/logrocket_deno_api, and in config.js, I edited line 1 from const env = Deno.env() to const env = Deno.env, since it looks like Deno.env became an object instead of a method.
The tutorial is not using versioned URLs, and deno-postgres version that is being used is not compatible with v0.42.0, since https://deno.land/x/postgres/mod.ts is pulling from master
Change db/database.js to import from https://deno.land/x/postgres#v0.3.11/mod.ts, since v0.3.11 is the correct version for Deno v0.42.0
import { Client } from "https://deno.land/x/postgres#v0.3.11/mod.ts";
Remember to always use the version in the URL if you don't want the code to stop working when a new Deno or package version is released.
I am using Lodash orderBy() to sort some data in my app.
const sorted = _.orderBy(dataCollection, ['startTime'], ['desc']);
This was working great until I created a production webpack build with uglify / minification which then gave the error:
TypeError: t is not a function
How should I change my code to properly handle obfuscation?
I found this thread on the lodash site that describes a similar problem with sortBy(). The solution was to create an function to access the data properties rather than a string property name.
const sorted = _.orderBy(dataCollection, [(data) => data.startTime], ['desc']);
To make random strings in pug template I want to use random-string javascript module.
First I install it via npm like this :
npm install random-string
Then in pug template I used this :
.site
.title
- var string = randomString({length: 20});
| #{string}
But while compiling files I got this error :
randomString is not a function
How Can I use third party javascript functions in pug js temaplte?
Your pug file won't have scope of randomString unless it is passed in when you call render() in your file that is calling it (such as your controller).
e.g.
this.render("[pugFilename]", {
randomString = require("randomstring") // whatever package name you're using
}
Personally, I prefer doing any non-view stuff outside the view and in the script that is requesting the view to be rendered, where I can.
The syntax in Pug can start to look very messy otherwise and become difficult to follow.
You can switch out the code above with the code in your question and it should work fine, although I'd recommend changing your variable name (or key) to something more meaningful.
e.g
this.render("[pugFilename]", {
randomStr: randomString({ length: 20 })
});
Update for phpStorm File Watcher
Firstly, install pug-cli and random-string locally,
npm install pug-cli random-string --save
Then setup File Watcher,
Original answer
Set and require random-string as a local variable, then you can access it in the templates. For example,
template.pug
.site
.title
- var string = randomString({length: 20});
| #{string}
compile it using pug
const pug = require('pug');
// Compile template.pug, and render a set of data
console.log(pug.renderFile('template.pug', {
randomString: require('random-string')
}));
//-> <div class="site"><div class="title">o0rGsvgEEOHrxj7niivt</div></div>
If you are using pug-cli, install random-string in the same scope of pug-cli, and specify options through a string or a file.
pug -O "{randomString: require('random-string')}" template.pug
This question already has answers here:
PowerShell: Setting an environment variable for a single command only
(10 answers)
Closed 4 years ago.
I'm trying pass an environment variable to Node.js with PowerShell like this way:
C:\Users\everton\my-project> $env:MY_VAR = 8000 node index.js
But I get an error in PowerShell:
Token 'node' unexpected expression or statement
Set environmental variable MY_VAR first and run your app like this:
C:\Users\everton\my-project> $env:MY_VAR="8000" ; node index.js
You can access environmental variable MY_VAR inside index.js by
process.env.MY_VAR
Note: PowerShell doesn't directly support command-scoped environment variables. The above command sets the environment variable for that PowerShell session.
My answer require the use of Node.js and npm libraries.
...or you just take out the pain of writing obscure-WTF-language-scripting, and use one of command-scoped (plus cross-platform) Node.js scripts:
cross-env (for inline)
cross-env MYVAR=MYVALUE node index.js
env-cmd (from .env file)
env-cmd .env node index.js
with
#.env file
MYVAR=MYVALUE
Note: If you can assume that Node.js is already installed - as is by definition the case when you're invoking node - consider use of npm helper packages, as shown in Cyril CHAPON 's helpful answer.
This answer focuses on generic solutions from within PowerShell.
tl;dr
# Set env. variable temporarily, invoke the external utility,
# then remove / restore old value.
$oldVal, $env:MYVAR = $env:MYVAR, 8000; node index.js; $env:MYVAR = $oldVal
# Scoped alternative that uses a *transient* helper variable.
& { $oldVal, $env:MY_VAR = $env:MY_VAR, 8000; node index.js; $env:MY_VAR = $oldVal }
More simply, if there's no preexisting MY_VAR value that must be restored.
$env:MYVAR=8000; node index.js; $env:MYVAR=$null
See below for an explanation and an alternative based on a helper function.
To complement Harikrishnan's effective answer:
PowerShell has no equivalent to the command-scoped method of passing environment variables that POSIX-like shells offer (as of PowerShell v7 - however, introducing it to PowerShell - not necessarily with the same syntax - is being discussed in GitHub issue #3316); e.g.:
# E.g., in *Bash*:
# Define environment variable MY_VAR for the child process being invoked (`node`)
# ONLY; in other words: MY_VAR is scoped to the command being invoked
# (subsequent commands do not see it).
MY_VAR=8000 node index.js
In PowerShell, as Harikrishnan's answer demonstrates, you have to define the environment variable first, and then, in a separate statement, call the external program, so $env:MY_VAR="8000"; node index.js is the right PowerShell solution, but it is worth nothing that $env:MY_VAR stays in scope for the remainder of the session (it is set at the process level).
Note that even using a script block invoked with & to create a child scope doesn't help here, because such child scopes only apply to PowerShell variables, not environment variables.
You can, of course, remove the environment variable manually after the node call:
Remove-Item env:MY_VAR or even just $env:MY_VAR = $null, which is what the 1st command at the top shows.
A more structured alternative - perhaps better in the case of setting multiple environment variables and/or invoking multiple commands - is to use a script block invoked with &:
& { $oldVal, $env:MY_VAR = $env:MY_VAR, 8000; node index.js; $env:MY_VAR = $oldVal }
This takes advantage of:
{ ... } is a script block that provides a clearly visible grouping for the commands in it; invoked with &, it creates a local scope, so that helper variable $oldVal automatically goes out of scope on exiting the block.
$oldVal, $env:MY_VAR = $env:MY_VAR, 8000 saves the old value (if any) of $env:MY_VAR in $oldVal while changing the value to 8000; this technique of assigning to multiple variables at once (known as destructuring assignment in some languages) is explained in Get-Help about_Assignment_Operators, section "ASSIGNING MULTIPLE VARIALBES".
Alternatively, use the helper function below, or use a try { ... } finally { ... } approach, as demonstrated in this related answer.
Helper function for command-scoped environment modifications.
If you define the helper function below (remember that function definitions must be placed before they're invoked), you can achieve command-scoped modification of your environment as follows:
# Invoke `node index.js` with a *temporarily* set MY_VAR environment variable.
Invoke-WithEnvironment #{ MY_VAR = 8000 } { node index.js }
Invoke-WithEnvironment() source code:
function Invoke-WithEnvironment {
<#
.SYNOPSIS
Invokes commands with a temporarily modified environment.
.DESCRIPTION
Modifies environment variables temporarily based on a hashtable of values,
invokes the specified script block, then restores the previous environment.
.PARAMETER Environment
A hashtable that defines the temporary environment-variable values.
Assign $null to (temporarily) remove an environment variable that is
currently set.
.PARAMETER ScriptBlock
The command(s) to execute with the temporarily modified environment.
.EXAMPLE
> Invoke-WithEnvironment #{ PORT=8080 } { node index.js }
Runs node with environment variable PORT temporarily set to 8080, with its
previous value, if any
#>
param(
[Parameter(Mandatory)] [System.Collections.IDictionary] $Environment,
[Parameter(Mandatory)] [scriptblock] $ScriptBlock
)
# Modify the environment based on the hashtable and save the original
# one for later restoration.
$htOrgEnv = #{}
foreach ($kv in $Environment.GetEnumerator()) {
$htOrgEnv[$kv.Key] = (Get-Item -EA SilentlyContinue "env:$($kv.Key)").Value
Set-Item "env:$($kv.Key)" $kv.Value
}
# Invoke the script block
try {
& $ScriptBlock
} finally {
# Restore the original environment.
foreach ($kv in $Environment.GetEnumerator()) {
# Note: setting an environment var. to $null or '' *removes* it.
Set-Item "env:$($kv.Key)" $htOrgEnv[$kv.Key]
}
}
}