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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (2)

Collapse
 
ayoubmehd profile image
Ayoub

Thanks, that is very useful

Collapse
 
christianfei profile image
Christian

Glad it was helpful!