0

I'm currently converting some code from Node JavaScript into TypeScript

I have a file called keys.js

let keys;
try {
  // eslint-disable-next-line security/detect-non-literal-fs-filename
  keys = JSON.parse(fs.readFileSync(credsPath, 'utf8'));
} catch (error) {
  return logger.error('initKeysParseError', error, { credsPath });
}

if (keys) {
  logger.info('initKeysSuccess', 'keys ready', null);

  return (module.exports.keys = keys);
}

return logger.error('initKeysError', null, { credsPath });

And when I wanted to use keys in another file, I would

const { keys } = require('./keys');
console.log(keys.account.username);

I'm having some issue doing this in typescript

How can I initialize the keys variable only once and then be able to do import keys from './keys';

?

Thanks!

2 Answers 2

1

Haven't tried this but I think:

let keys;
try {
  // eslint-disable-next-line security/detect-non-literal-fs-filename
  keys = JSON.parse(fs.readFileSync(credsPath, 'utf8'));
  if (keys) {
    logger.info('initKeysSuccess', 'keys ready', null);
  } else {
    logger.error('initKeysError', null, { credsPath });
  }
} catch (error) {
  logger.error('initKeysParseError', error, { credsPath });
}

export { keys };
Sign up to request clarification or add additional context in comments.

Comments

1

I think, you should wrap your code in keys.js in some function

exports.getKeys = function() {
  let keys;

  try {
    // eslint-disable-next-line security/detect-non-literal-fs-filename
    keys = JSON.parse(fs.readFileSync(credsPath, 'utf8'));
  } catch (error) {
    logger.error('initKeysParseError', error, { credsPath });
  }

  if (keys) {
    logger.info('initKeysSuccess', 'keys ready', null);
    return keys;
  }

  logger.error('initKeysError', null, { credsPath })
  return keys;
}
const module = require('./keys.js')
const keys = module.getKeys();

and maybe you should switch to use esnext module with import ... from ... syntax, you can do that by changing tsconfig.json compilerOptions to "module": "esnext"

1 Comment

I like it! But is there a way to not also have to do the .getKeys() part?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.