Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is process.env undefined in module?

I'm beginner with nodejs and I want environment variables shared through modules. I read those variables with dotenv package. But in next required module process.env is undefined.

app.js

console.log(require('dotenv').config())
console.log(process.env.NODE_ENV);
require('./task')

task.js

console.log(process.env);
console.log(process.env.NODE_ENV);

.env

NODE_ENV=development
PORT=8080

console log

{ parsed: { NODE_ENV: 'development', PORT: '8080' } }
development
undefined
E:\msf\nodejs_prj\compositor\task.js:2
console.log(process.env.NODE_ENV);
                        ^
TypeError: Cannot read property 'NODE_ENV' of undefined
    at Object.<anonymous> ...

I created new clean project with provided code and it works also for me. That means it's related to something else. This node.js is weard about errors.

This is my whole code from task.js

const fs = require('fs')
const path = require('path')
const decompress = require('decompress')

const dir = './upload'

console.log(process, process.env)

function process() {
    console.log('cron - process data');

    fs.readdir(dir, (err, files) => {
        if (err) return

        files.forEach(file => {
            if (path.extname(file) != '.zip') return

            let target = path.join(dir, path.basename(file).replace(path.extname(file), ''))
            unlinkDirSync(target)

            decompress(path.join(dir, file), target).then(files => {
                console.log(files);
                console.log('done!');

                //todo process unzipped files

                //todo delete unzipped directory and zip file
            })
        })
    })
}

function unlinkDirSync(dir_path) {
    if (fs.existsSync(dir_path)) {
        fs.readdirSync(dir_path).forEach(function (entry) {
            var entry_path = path.join(dir_path, entry);
            if (fs.lstatSync(entry_path).isDirectory()) {
                unlinkDirSync(entry_path);
            } else {
                fs.unlinkSync(entry_path);
            }
        });
        fs.rmdirSync(dir_path);
    }
}

if (process.env === undefined || process.env.NODE_ENV === undefined || process.env.NODE_ENV === 'production') {
    console.log('starting on production')
    setInterval(process, 1000 * 60)
} else {
    console.log('starting on development')
    setTimeout(process, 1000)
}

If I comment out the rest after console.log it works.

like image 542
oLDo Avatar asked Dec 02 '22 10:12

oLDo


1 Answers

I'm idiot. I named function process, which is the name of system variable :D

Sorry for bothering you guys, thanks for help.

like image 75
oLDo Avatar answered Dec 23 '22 03:12

oLDo