DEV Community

Christian
Christian

Posted on • Originally published at cri.dev

3 2

Simple .npmrc management

Originally posted on cri.dev

One way to provide environment variables when running a script with npm, is to create a file called .npmrc in the root of the project (same level as package.json).

Here is an example .npmrc (note: lowercase):

telegram_token=abc
telegram_chat_id=123
Enter fullscreen mode Exit fullscreen mode

git ignore this file, especially in public repos

I find it useful to have an npm script called node, which runs node, but by loading the .npmrc file:

In your package.json

  "scripts": {
    "node": "node",
    ...
Enter fullscreen mode Exit fullscreen mode

Then, in your Node.js script, you would read the environment variables with the npm_config_ prefix.

You can run this now with npm run node -- index.js

The index.js file:

console.log(process.env.npm_config_telegram_token)
> abc
console.log(process.env.npm_config_telegram_chat_id)
> 123
Enter fullscreen mode Exit fullscreen mode

Here is how I personally manage my environments in Node.js.

Example

Below you can find an example using the library simple-telegram-message:

const { sendMessageFor } = require('simple-telegram-message')
const sendMessage = sendMessageFor(process.env.npm_config_telegram_token, process.env.npm_config_telegram_chat_id)
sendMessage(`Hi from bot!`)
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (2)

Collapse
 
ayoubmehd profile image
Ayoub

Thanks, that is very useful

Collapse
 
christianfei profile image
Christian

Glad it was helpful!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay