Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define const in nodejs in global scope?

Tags:

node.js

I want to separate my app in to the parts to have something like MVC... Currently I figured out exports works and how to communicate between different files. The one thing i cant understand is that how to use constants in global scope? Currently i have something like this:

// start.js

const ROOT_DIR = __dirname;
const APP_DIR = ROOT_DIR + '/app/';
const MODULES_DIR = '/usr/local/lib/node_modules/';
const APP_PORT = 4935;

var server = require(APP_DIR + 'server.js');

server.start();

// server.js

exports.start = function() {
    var express = require(MODULES_DIR + 'express'),
        app = express(),
        http = require('http'),
        server = http.createServer(app),
        io = require(MODULES_DIR + 'socket.io').listen(server),
        fs = require('fs'),
        path = require('path');

    server.listen(APP_PORT);

    app.use(express.static(ROOT_DIR + '/assets'));

    app.get('/', function (req, res) {
        res.sendfile(ROOT_DIR + '/views/index.html');
    });
}

Is it possible to automatically assign this constants to server.js or i need to pass them as variables?

like image 928
Kin Avatar asked Nov 27 '13 10:11

Kin


People also ask

Can we use const in global scope?

Variables declared outside of any functions and blocks are global and are said to have Global Scope . This means you can access them from any part of the current JavaScript program. You can use var , let , and const to declare global variables.

How do you declare a constant in node JS?

Defining constants is as simple as setting the webpack config file: var webpack = require('webpack'); module. exports = { plugins: [ new webpack. DefinePlugin({ 'APP_ENV': '"dev"', 'process.

Is const global variable?

It is not a property of the global object (because const , let , and class don't create properties on the global object), but it is a global constant accessible to all code running within that global environment.

Does const have scope?

const declarations are block scoped Like let declarations, const declarations can only be accessed within the block they were declared.


1 Answers

Object.defineProperty(global, 'MY_CONST', { value : 123 })

P.S. Please, don't do this

like image 134
vkurchatkin Avatar answered Nov 07 '22 05:11

vkurchatkin