Reputation: 13
Im using NestJS framework to build a rest api, i have a issue getting the environment variables.
I have a .env with a variable "SMB_SHARE" with a path string, when i pass this variable to a class constructor of a smb2 libray, this throw an error, the string provided by the environment variable is invalid.
The environment variable is this:
SMB_SHARE=\\10.00.0.000\some_path
When i use console log in the code the variable is ok, is a string and has the correct string value. But when i pass it to the constructor, it throw the error.
I pass the string directly to the constructor, and it work fine, the others environment variables of the constructor are setted correctly (like the username and password). Only the SMB_SHARE variable is throwing the error.
I dont have idea what is the problem here. Can someone help me with this issue?
I show some examples:
constructor(private config: ConfigService) {
console.log('VAR', config.get<string>('SMB_SHARE'));
//This show the correctly string variable value
const share = config.get<string>('SMB_SHARE');
this.sambaClient = new SMB2({
share: '\\\\10.00.0.000\\some_path', //WORK
//share: share, FAIL
//share: config.get<string>('SMB_SHARE'), FAIL
//share: process.env.SMB_SHARE, FAIL
domain: '',
username: config.get<string>('SMB_USERNAME'),
password: config.get<string>('SMB_PASSWORD'),
debug: true,
autoCloseTimeout: 0,
})
}
The .env file is like this:
SMB_SHARE=\\\\10.00.0.000\\some_path
SMB_USERNAME=user
SMB_PASSWORD=secret
Upvotes: 0
Views: 1087
Reputation: 70151
More than likely, what is happening is JavaScript is escaping the extra \
. This is unescaped when the print happens, so it looks proper (i.e. console.log(process.env.SMB_SHARE)
will print \\\\10.0.0.0\\some_path
, but in reality, the variable is now \\\\\\\\10.0.0.0\\\\some_path
). I ended up creating a mock of this using a text file called ./temp/.env
and making use of the fs
module from Node (which is what dotenv
uses, which is what @nestjs/config
uses. You can see below the cat
(print) of the file, and the two different methods while using node
to read the file
~/Documents/code
▶ cat ./temp/.env
HOST=\\\\127.0.0.1:3000\\path
~/Documents/code
▶ node
Welcome to Node.js v12.18.2.
Type ".help" for more information.
> const { readFileSync } = require('fs');
undefined
> readFileSync('./temp/.env').toString()
'HOST=\\\\\\\\127.0.0.1:3000\\\\path\n\n'
> console.log(readFileSync('./temp/.env').toString())
HOST=\\\\127.0.0.1:3000\\path
The solution here, would be to change your .env
file to be the exact string you're wanting to pass on to the configuration (probably \\10.0.0.0\some_path
)
Upvotes: 1
Reputation: 2987
you have to implement the config module.
start with
npm i --save @nestjs/config
then add the configModule in your appModule:
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [ConfigModule.forRoot()],
})
export class AppModule {}
Upvotes: 0