Defining a property via process.env in javascript

318 views Asked by At

I'm new to JavaScript and stuck. I'm writing my first "real" Electron App and want to connect via sftp. (ssh2-sftp-client to be more specific) When I set up the connection like the example:

sftp.connect({
  host: '192.168.76.173',
  port: '22',
  username: 'Backup',
  password: 'PasswordInPlainText'
}).then(() => {
  return sftp.list('/Backups/Server');
}).then(data => {
  console.log(data, 'the data info');
}).catch(err => {
  console.log(err, 'catch error');
});

everything works like a charm. But when I try to "hide" my credentials in an .env file:

sftp.connect({
    host: process.env.HOST,
    port: process.env.PORT,
    username: process.env.USERNAME,
    password: process.env.PASSWORD
}).then(() => {
  return sftp.list('/Backups/Server');
}).then(data => {
  console.log(data, 'the data info');
}).catch(err => {
  console.log(err, 'catch error');
});
I get the error message:

Error: connect: getConnection: All configured authentication methods failed

I checked via

console.log("Host to connect: "+ process.env.HOST)
and the correct output is:

Host to connect: 192.168.76.173

The content of the .env File is

    HOST='192.168.76.173'
    PORT='22'
    USERNAME='Backup'
    PASSWORD='PasswordInPlainText'

So this my first time working with environment Variables at all, so I'm guessing I misunderstood something, or a JavaScript property can't be defined by a string this way.

1

There are 1 answers

3
Nikolay Babanov On

Your problem is that the .env files are not supported in NodeJS by default and you might have some env variables already with the same names and different values (defined in the system probably).

You could either use a NPM package like dotenv or parse the contents of the file by yourself.

You could also test it like that:

// Place this code before you use the ENV variables.
// Replace the `<variables>` with the real data
// and test if your code works with the ENV variables. 
process.env.HOST = '<your host ip>';
process.env.PORT = '<your port>';
process.env.USERNAME = '<username>';
process.env.PASSWORD = '<password>';