Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Beginners

    The Concept of Scope in JavaScript

    Programming

    How To Use Prospector For Python Static Code Analysis

    Interview

    Effective Strategies for Acing Part-Time Job Interviews

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Programming / 2. Express.js Lessons. Logger, Configuration, Templating with EJS. Part 1.
    Programming

    2. Express.js Lessons. Logger, Configuration, Templating with EJS. Part 1.

    Ivan RastvorovBy Ivan RastvorovNovember 29, 2016Updated:April 5, 2019No Comments4 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    2. Express.js Lessons. Logger, Configuration, Templating with EJS. Part 1.
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    express_21n

    Hey all! To develop our app further, we need to do two more vital things – configuration and logging. We will use the nconf  module for configuring:

    npm i nconf

    It is definitely a weak idea to write port 3000 in the app and further specify connection to the database and so on. So, we put nconf  and now can look at documentation. We can configure the module, which means we connect it and then tell to this module where it can read configuration. The line is:

     nconf.argv()
       .env()
       .file({ file: 'path/to/config.json' });

    Which means: read configuration from the command line, environment variables and files. Let us now create config directory, create index.js in it and connect nconf there. Next copy configuration from the documents into it changing it a little bit (the file will be from the current directory), specify the path:

    var nconf = require('nconf');
    var path = require('path');
    
    nconf.argv()
        .env()
        .file({ file: path.join(__dirname, 'config.json') });
    
    module.exports = nconf;

    In the first config (create the file config inside our new directory  – config.json) let us write: port: 3000.

    {
      "port": 3000
    }

    Attach the config module to app.js:

    var config = require('config');

     change the launch configuration a little bit for it to find this module and add NODE_PATH.
    node_path
    Also, within app.js add the method 
    config.get:

    app.set('port', config.get('port'));
    
    http.createServer(app).listen(app.get('port'), function(){
      console.log('Express server listening on port ' + config.get('port'));
    });

    Check it. Everything works!

    The next thing we should do is to install a logger:

    npm i winston

    We will use our own wrap over winston. In order to find the right place for putting it, create the directory libs. Here we will put those modules and files that do not fall out anywhere, but we still some place for them. In our case, logging is the file log.js, (create it), which will be in this directory. Here is an example of such wrapping:

    var winston = require('winston');
    var ENV = process.env.NODE_ENV;
    
    // can be much more flexible than that O_o
    function getLogger(module) {
    
        var path = module.filename.split('').slice(-2).join('');
        return new winston.Logger({
            transports: [
                new winston.transports.Console({
                    colorize: true,
                    level: (ENV == 'development') ? 'debug' : 'error',
                    label: path
                })
            ]
        });
    }
    
    module.exports = getLogger;

    We get the environment. In our file log.js we’ll get the environment directly from NODE_ENV. In order to make it work, let us add the launch configuration with NODE_ENV development.

    node_path2

    What does this wrap do? If someone anchors a logger (let us add the record to app.js) , for example:

    var log = require('libs/log')(module);
    

    the function getLogger takes a module and generates a special logger object for it. It may have some transporting means activated or switched off, a correct logging level, and so on. The only difference is a mark. So, let us see what thing it is and how it will work.

    Read More:  Full Node.js Course

    Take the logger and do log.info instead of console.log:

    http.createServer(app).listen(app.get('port'), function(){
      log.info('Express server listening on port ' + config.get('port'));
    });
    

    Launch it. The logger outputs everything first in different colors, second – if there is development, it outputs the debug level and above, while remaining on production, if outputs error. In this case, we’ve got development, so everything is visible for us.

    Moreover, the logger has a mark:

    ....node_js_lessonsapp.js]

    which means what its original file was. Sometimes it is very interesting to know such things. So, we take module.filename and get 2 last elements of the path. Let’s move on now.

    We will work on outputting a standard HTML page. We’ve got some Middlewares, but we will cut them and take the Middlewares built into Express. So, we need the settings:

    // app.set('views', __dirname + '/views');
    // app.set('view engine', 'ejs');

    These are the settings for a templating system, while our template engine will be ejs. Let us change the name of our views directory to templates. You may have any other templating system in your case – in fact, there are many of them. We will get rid of the port because there is obviously no reason to add it inside the app:

    // app.set('port', process.env.PORT || 3000);
    app.set('port', config.get('port'));<br>

    Let us do a normal config and take settings out of it. Moreover, we will add other Middlewares that we’ve got. Our app.js will look like:

    var express = require('express');
    var http = require('http');
    var path = require('path');
    var config = require('config');
    var log = require('libs/log')(module);
    
    
    var app = express();
    app.set('views', __dirname + '/templates');
    app.set('view engine', 'ejs');
    
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser('your secret here'));
    app.use(express.session());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.use(function(err, req, res, next) {
      // NODE_ENV = 'production'
      if (app.get('env') == 'development') {
        var errorHandler = express.errorHandler();
        errorHandler(err, req, res, next);
      } else {
        res.send(500);
      }
    });
    
    // var routes = require('./routes');
    // var user = require('./routes/user');
    
    // // all environments
    
    // app.get('/', routes.index);
    // app.get('/users', user.list);
    
    
    http.createServer(app).listen(config.get('port'), function(){
      log.info('Express server listening on port ' + config.get('port'));
    });
    

    Please stay tuned, we’ll continue in th nx article!

    Read More:  50+ Amazing Tools and Online Resources for Web Developers | Bookmark Now!

    The lesson code can be found  here.

    to-be-continued-series-8

    The materials for this article have been borrowed from the following screencast.

    We are looking forward to meeting you on our website blog.soshace.com

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Ivan Rastvorov
    • Website

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024

    Effective Strategies for Utilizing Frameworks in Web Development

    December 16, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    JavaScript March 20, 2020

    React Lesson 11. Pt.1: Normalize Comments with Immutable.js

    Our previous lesson was devoted to a more convenient way of how to write reducers using seamless APIs to add/remove elements and not to worry about any processes to be changed in between.

    The Impact of Integrated Development Environments on Programming

    November 28, 2024

    Analyzing Future Fintech Marketing Trends: Insights Ahead

    August 27, 2025

    Strategic Approaches to Securing Startup Funding Successfully

    December 10, 2024

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Стиль кода

    Programming January 11, 2016

    How to pay your foreign remote workers?

    JavaScript October 9, 2018

    23. Уроки Node.js. Домены, “асинхронный try..catch”. Часть 3.

    Programming November 18, 2016

    10 Hiring Lessons from Silicon Valley: for Small and Large Companies

    JavaScript January 31, 2019

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    JavaScript

    Node.js Lesson 13: Debugging in Node.js

    LinkedIn

    Maximizing Lead Generation with LinkedIn InMail Strategies

    Consultation

    Best Background Check Services Assessments

    Most Popular

    Strategies for Overcoming Prospecting Objections on LinkedIn

    LinkedIn

    Новичкам

    Wiki

    List of Coding Games to Practice & Improve Your Programming Skills

    Beginners
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.