Snippets Collections
// From postman:
{
    "select": {"productName": "Skykick"}
}

// In file:
    req.body.select,
{
  "name": "frontend",
    // add proxy, so instead of looking at front end server, our api requests look at backend server
    // call it prox, then add the loopback address and the backend server port
  "proxy": "http://127.0.0.1:8080",
  "version": "0.1.0",
const express = require('express');
const router = express.Router();

// this is our crud route so it'll have the most routes
// SIGNTAURE TYPE ENDPOINT
// @route       GET api/contacts
// @desc        get user's contacts
// @access      private (theses are all private to user so all private)
// we said anything that goes to this file is coming from /api/auth so we just need a slash
router.get('/', (req, res) => {
    res.send(`Get all the user's contacts`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       POST api/contacts
// @desc        add a new contact
// @access      private 
router.post('/', (req, res) => {
    res.send(`Add a new contact`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       PUT api/contacts/:id (we need to id which contact is getting updated)
// @desc        update contact
// @access      private 
router.put('/:id', (req, res) => {
    res.send(`Update a contact`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       DELETE api/contacts/:id (we need to id which contact is getting deleted)
// @desc        delete contact
// @access      private 
router.delete('/:id', (req, res) => {
    res.send(`DESTROY a contact`)
})

// export router so we can access ittttt
module.exports = router
// require mongoose
const mongoose = require('mongoose');
// require config file to access mongoURI 
const config = require('config');
// make our db the mongoURI
const db = config.get('mongoURI');

const connectDB = async () => {
    try {
       await mongoose.connect(db, {
            useNewUrlParser: true,
            useCreateIndex: true,
            useUnifiedTopology: true,
            useFindAndModify: false
        })
        console.log('mongo db connected')
    } catch (err) {
        console.error(err)
        //exit with failure
        process.exit(1)
    }
}

module.exports = connectDB;
//To see all versions of Node that are installed on your machine use the command:
$ npm -v

//To see versions installed on machine

$ nvm ls
->      v16.1.0
         system
default -> node (-> v16.1.0)
iojs -> N/A (default)
unstable -> N/A (default)
node -> stable (-> v16.1.0) (default)
stable -> 16.1 (-> v16.1.0) (default)

// add a new version
$ nvm install <version>
  
// to switch to a different verison
  
$ nvm use <version>
const getSourcesData = asyncHandler(async (req, res) => {
  const { dealership } = req.user;
  const month = parseInt(req.params.month);
  const customerData = await Customer.aggregate()
    .match({ dealership })
    .facet({
      fbCount: [
        {
          $match: {
            sourceOfEnquiry: "Facebook",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "fbCount" },
      ],
      googleCount: [
        {
          $match: {
            sourceOfEnquiry: "Google",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },

        { $count: "googleCount" },
      ],
      cardekhoCount: [
        {
          $match: {
            sourceOfEnquiry: "Cardekho",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "cardekhoCount" },
      ],
      carwaleCount: [
        {
          $match: {
            sourceOfEnquiry: "Carwale",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "carwaleCount" },
      ],
      instagramCount: [
        {
          $match: {
            sourceOfEnquiry: "Instagram",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "instagramCount" },
      ],
      newspaperAdsCount: [
        {
          $match: {
            sourceOfEnquiry: "Newspaper Ads",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "newspaperAdsCount" },
      ],
      websiteCount: [
        {
          $match: {
            sourceOfEnquiry: "Website",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "websiteCount" },
      ],
      hoardingsCount: [
        {
          $match: {
            sourceOfEnquiry: "Hoardings",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "hoardingsCount" },
      ],
      telephonicCount: [
        {
          $match: {
            sourceOfEnquiry: "Telephonic",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "telephonicCount" },
      ],
      referralCount: [
        {
          $match: {
            sourceOfEnquiry: "Referral",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "referralCount" },
      ],
      workshopCount: [
        {
          $match: {
            sourceOfEnquiry: "Workshop",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "workshopCount" },
      ],
      bushfireCount: [
        {
          $match: {
            sourceOfEnquiry: "Bushfire",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "bushfireCount" },
      ],
      managementCount: [
        {
          $match: {
            sourceOfEnquiry: "Management",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "managementCount" },
      ],
      walkInCount: [
        {
          $match: {
            sourceOfEnquiry: "Walk-in",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "walkInCount" },
      ],
    });
  

  return res.status(200).json({
    success: true,
    tableData: customerData,
  });
});
{
  sourceOfEnquiry:'Telephonic',
    createdAt: {
        $gte: ISODate("2021-06-01T00:00:00.000Z"),
        $lte: ISODate("2021-06-30T00:00:00.000Z")
    }
}
db.users.updateMany(
  { __t: "SE" },
  {
    $set: {
      targets: [
        {
          modelName: "rapid",
          targetCount: 15,
          bookingCount: 0,
          deliveredCount: 0,
        },
        {
          modelName: "superb",
          targetCount: 10,
          bookingCount: 0,
          deliveredCount: 0,
        },
        {
          modelName: "kushaq",
          targetCount: 5,
          bookingCount: 0,
          deliveredCount: 0,
        },
        {
          modelName: "octavia",
          targetCount: 0,
          bookingCount: 0,
          deliveredCount: 0,
        },
      ],
    },
  }
);
//create a file test.rest:
GET http://localhost:5000
# Push the commit and update the deployed version on Heroku
git push heroku main

# Open the app in the browser (from terminal)
heroku open

#fetch heroku logs
heroku logs

#specify number of logs
heroku logs -n 200

#find all your fucking heroku deployment errors then cry yourself to sleep
heroku logs --tail

# Open the terminal in the app dyno in Heroku
heroku run bash
 
# Run a file 
node seeds/index.js
# Open the terminal in the app dyno in Heroku

heroku run bash

 

# We may then run the seed file

node bin/seed.js
const dateFilter = asyncHandler(async (req, res) => {
  const month = 7;
  const day = 13;
  const feedbacks = await Feedback.find({
    $expr: {
      $or: [
        {
          $and: [
            { $eq: [{ $month: "$birthday" }, month] },
            { $eq: [{ $dayOfMonth: "$birthday" }, day] },
          ],
        },
        {
          $and: [
            { $eq: [{ $month: "$anniversary" }, month] },
            { $eq: [{ $dayOfMonth: "$anniversary" }, day] },
          ],
        },
      ],
    },
  });
  res.send(feedbacks);
});
const dateFilter = asyncHandler(async (req, res) => {
  const month = 6;
  const day = 10;
  const feedbacks = await Feedback.find({
    $expr: {
      $or: [
        {
          $eq: [{ $month: "$birthday" }, month],
          $eq: [{ $dayOfMonth: "$birthday" }, day],
        },
        {
          $eq: [{ $month: "$anniversary" }, month],
          $eq: [{ $dayOfMonth: "$anniversary" }, day],
        },
      ],
    },
  });
  console.log({ feedbacks });
});
hbs.registerHelper(`iff`, function (a, operator, b, opts) {
    let bool = false;
    a.toString();
    b.toString();
    switch (operator) {
        case `===`:
            bool = a === b;
            break;
        case `>`:
            bool = a > b;
            break;
        case `<`:
            bool = a < b;
            break;
        default:
            bool = a === b;
    }

    if (bool) {
        return opts.fn(this);
    }
    return opts.inverse(this);
});

{{#iff value1 '>' value2}}
do the thing
{{/iff}}
//cons name = 'me'

{{log 'author = ' name }}

//author = me
// in app.js
hbs.registerHelper(`ifEquals`, function (a, b, opts) {
    if (a.toString() === b.toString()) {
        return opts.fn(this);
    }
    return opts.inverse(this);
});

// in hbs template
{{#ifEquals name 'Foo'}}
      true
{{else}}
      false
{{/ifEquals}}
const comparePassword = async (password, hash) => {
    try {
        // Compare password
        return await bcrypt.compare(password, hash);
    } catch (error) {
        console.log(error);
    }

    // Return false if error
    return false;
};

//use case
(async () => {
    // Hash fetched from DB
    const hash = `$2b$10$5ysgXZUJi7MkJWhEhFcZTObGe18G1G.0rnXkewEtXq6ebVx1qpjYW`;

    // Check if password is correct
    const isValidPass = await comparePassword('123456', hash);

    // Print validation status
    console.log(`Password is ${!isValidPass ? 'not' : ''} valid!`);
    // => Password is valid!
})();
const mongoose = require('mongoose');

const server = '127.0.0.1:27017'; // REPLACE WITH YOUR OWN SERVER
const database = 'test';          // REPLACE WITH YOUR OWN DB NAME

const connectDB = async () => {
    try {
        await mongoose.connect(`mongodb://${server}/${database}`, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useFindAndModify: false,
            useCreateIndex: true
        });

        console.log('MongoDB connected!!');
    } catch (err) {
        console.log('Failed to connect to MongoDB', err);
    }
};

connectDB();
function promiseWrapper(fn) {
    return (req, res, next) => {
         fn(req, res).catch(next);
    };
}
Using Git and Heroku

1) In terminal - git init

This creates a hidden file .git

2) git add .

This will creating a new copy of the work. This is a staging area.

3) git commit -m "Initial Commit"

This will making a commit of the version

[ These stages can be done using GitHub Desktop]

4) Then on terminal: heroku login

This will offers to open a browser. On the window that opened log in and close the window. 

5) $ heroku git:remote -a <name> if already created on heroku - or -   heroku create

this will show something like this in terminal:

https://still-gorge-92777.herokuapp.com/ | https://git.heroku.com/still-gorge-92777.git

6) Create Procfile

$ touch Procfile 

7) Find Procfile (should be empty) and add: web: node app.js (same file as we use for starting the application with nodemon).

8) Need to change port address to heroku’s dynamic port:

let port = process.env.PORT;if (port == null || port == "") { port = 3000;};app.listen(port, function () { console.log("Server started successfully");});

9) Choose a database host - we already have that so ignore.

10) Language specific setup: 

Need to specify the version of node to heroku:

in terminal: $ node --version, 

then in package.json add: 

"engines": { "node": "12.x" } [or whatever version. No need to be totally specific hence the ‘x’]. Can insert before the dependencies start.

11) Create .gitingnore file:

touch .gitignore and in .gitignore: 

/node_modules

npm-debug.log.

DS_Store

/*.env

12) Deploy on heroku: 

Before deploying - push to git one more time for last changes to be added:

git add . 

git commit -m “<chanages made to go in here>”

$ git push heroku master

[note: at this point I had an error message: ‘error: src refspec master does not match any’.

I needed to change the branch from ‘main’ on the bottom left of vs code to ‘master’ by adding a branch master through vs code. I then pushed again and it worked.]

Committing directly to git:

https://stackoverflow.com/questions/46877667/how-to-add-a-new-project-to-github-using-vs-code - below is the relevant content:

1) Navigate to the local project directory and create a local git repository: (already done above)

 git init


2) Once that is successful, click on the 'Source Control' icon on the left navbar in VS-Code.One should be able to see files ready to be commit-ed. Press on 'Commit' button, provide comments, stage the changes and commit the files. Alternatively you can run from CLI (already done abovre)

git commit -m "Your comment"


3) Now you need to visit your GitHub account and create a new Repository. Exclude creating 'README.md', '.gitIgnore' files. Also do not add any License to the repo. Sometimes these settings cause issue while pushing in.

4) Copy the link to this newly created GitHub Repository.

5) Come back to the terminal in VS-CODE and type these commands in succession:

git remote add origin <Link to GitHub Repo>     //maps the remote repo link to local git repo

git remote -v                                  //this is to verify the link to the remote repo 

git push -u origin master // or main                      // pushes the commit-ed changes into the remote repo

 6) You can see the success message in the Terminal. You can also verify by refreshing the GitHub repo online.

Once done can change branch used from master to main: 

To switch the default branch used to deploy apps from master to main, first create a new branch locally:

git checkout -b main


Next, delete the old default branch locally:

git branch -D master


From there, the local environment only knows about the main branch.

Reset the GIT repository hosted on the Heroku Platform using the heroku-reset command from the heroku-repo CLI plugin. Doing so will not impact the running application. (Note: Please communicate this change with your team. If you are working with other developers who are not aware of the reset, they might push to "master" which will overwrite the reset).

Re-deploy the application using the new default branch:

git push heroku main

To push directly to github: 

The git push command takes two arguments:

A remote name, for example, origin

A branch name, for example, main

For example:

git push  <REMOTENAME> <BRANCHNAME> 

app.get('/downloadFile', function (req, res) {
  var file = path.join(__dirname, '/pdfs/');
  res.download(file, function (err) {
    if (err) {
      console.log('Error');
      console.log(err);
    } else {
      console.log('Success');
    }
  });
});
test('should verify typed', async () => {
  const browser = await puppeteer.launch({
    headless: false,
    slowMo: 10,
    args: ['--window-size=1920,1080']
  })
  const page = await browser.newPage()
  await page.goto(url)
  await page.type('.input-text', 'Hello World!')

  const finalText = await page.$eval('input.input-text', el => el.textContent)
  expect(finalText).toBe(finalText)
})
const bookingNumber = `${_.upperCase(modelName)}${_.random(1000000, 9999999)}
const {getIntroduction} = require('./util')

test('should output name and age', () => {
  const text = getIntroduction('Max', 20)
  expect(text).toBe('Max is 20 years old')
})
"scripts": {
  "test": "jest",
   "start": "node index.js"
},
"devDependencies": {
  "jest": "^26.6.3"
}
let fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
const updateStatus = asyncHandler(async (req, res) => {
  console.log("k");
  const { customer, stageFiveId, availableLoansId, status } = req.body;
  console.log(req.body);
  const customerData = await Customer.updateMany(
    {
      _id: customer,
    },
    // db.coll.update({}, {$set: {“a.$[i].c.$[j].d”: 2}}, {arrayFilters: [{“i.b”: 0}, {“j.d”: 0}]})
    {
      $set: { "stage5.$[i].availableLoans.$[j].status": status },
    },
    { arrayFilters: [{ "i._id": stageFiveId }, { "j._id": availableLoansId }] }
  );
  console.log(customerData);
  if (customerData)
    return res.status(200).json({
      success: true,
      message: "Status updated sucessfully!",
    });
  else
    return res.status(400).json({
      success: false,
      message: "Could not able to update Status!",
    });
});
db.customers.updateMany({}, {$unset:{"customerName":1}})
db.customers.updateMany({}, {$unset:{"customerName":1}})
db.customers.updateMany({},
  [{ $set : { n : {$arrayElemAt:[{ $split: ["$customerName", " "] },1]}} }],

);
db.customers.updateMany({},
  [{ $set : { m : {$arrayElemAt:[{ $split: ["$customerName", " "] },0]}} }],

);
const fetch = require('isomorphic-fetch')


const query = fetch('https://www.freecodecamp.org/page-data/sq/d/4195245674.json')
    .then(resp => resp.json())
    .then(data => {
        // console.log(data)
        return data.data.allChallengeNode.edges.map(e => {
            // console.log(e.node)
            const url_pieces = e.node.fields.slug.split('/')
            return { 
                name: e.node.title, 
                cert: url_pieces[2], 
                section: url_pieces[3], 
                task: url_pieces[4] 
            }
        })
    }).then(q => console.log(q))
await new Promise(r => setTimeout(r, 5000));
const getModels = asyncHandler(async (req, res) => {
  const { modelName } = req.query;
  const dealership = await Dealership.aggregate([
    { $match: { _id: req.user.dealership } },
    {
      $project: {
        models: {
          $filter: {
            input: "$models",
            as: "models",
            cond: {
              $regexMatch: {
                input: "$$models.modelName",
                regex: `^${modelName}`,
                options: "i",
              },
            },
          },
        },
      },
    },
  ]);
  const models = dealership[0].models;
  return res.status(200).json({
    success: true,
    quesData: models,
  });
});
npx gsx-pdf-optimize raw_pdf.pdf optimized_pdf.pdf --dpi=150
// Script-wide timeout for wait and waitAndFind functions (in ms)
var startTime = new Date(),
  thisStep = 0,
  assert = require('assert'),
  Q = require('q'),
  ScriptTimeout = 0,
  MaintenanceMessage = "Script is running during maintenance window";

var log = function(msg) {
  if(typeof msg === "string")
  {
    var totalTimeElapsed = (new Date() - startTime);
    var elapsedSecs =  totalTimeElapsed / 1000;
    console.log('Step ' + thisStep + ': ' + elapsedSecs.toFixed(2) + 's: ' + msg);
    thisStep++;
    
    if(ScriptTimeout > 0 && totalTimeElapsed > ScriptTimeout)
    {
      throw Error('Script timed out. ' + totalTimeElapsed + 'ms is longer than script timeout threshold of ' + ScriptTimeout + 'ms.'); 
    }
  }
};

log("Initialising ...");

 // checks if this run is in within the maintenance window provided
 // @param {string} dayOfWeek - Monday, Tuesday, etc.
 // @param {string} startTime - UTC start time of window in 24hr format
 // @param {string} endTime - UTC end time of window in 24hr format
var checkInMaintenanceWindow = function(dayOfWeek, startTime, endTime)
{
  log("checkInMaintenanceWindow");
  var deferred = Q.defer();
  var daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  var now = new Date();
  var day = daysOfWeek[now.getUTCDay()];
  
  if(day != dayOfWeek)
  {
    log("Days do not match");
    deferred.resolve("Days do not match"); // not the specified day
  }
  else
  {
    log("Days match, checking times");
    startParts = startTime.split(":");
    var start = new Date(now);
    start.setUTCHours(parseInt(startParts[0]), parseInt(startParts[1]));

    endParts = endTime.split(":");
    var end = new Date(now);
    end.setUTCHours(parseInt(endParts[0]), parseInt(endParts[1]));

    // check if we are in the maintenance window
    if(now.getTime() >= start.getTime() && now.getTime() <= end.getTime())
    {
      log("In maintenance window");
      $http.get("http://www.google.co.uk"); // workaround for monitor produced no traffic error
      deferred.reject(MaintenanceMessage);
    }
    else
    {
      deferred.resolve("Times do not match");
    }
  }  
  return deferred.promise;
};

function shouldDisplayError(message)
{
  return !(typeof message != "undefined" && message !== null && message.length > 0);
}

var buildSecurityOptions = function()
{
  var deferred = Q.defer();
  log("Building security options");
  // build your security options here
  var options = {
    //Define endpoint URL.
    //url: "https://webhook.site/ddb04be2-8961-4771-b934-6dddfa40ab57",
    url: "https://login.salesforce.com/services/oauth2/token",
    //Define body of POST request.
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    form: {
      grant_type: 'password',
      client_id: 'client ID',
      client_secret: 'Client Secret',
      username: 'username',
      password: 'password'
    }
  };
  
  deferred.resolve(options); //fulfills the promise with options as the value
  return deferred.promise; //promise is returned
};

var getSecurityToken = function(options){
  var deferred = Q.defer();
  log("Retrieving Security Token");
  $http.post(options, function(error, response, body)
  {
    if (error)
    {
      log(error);
      deferred.reject(error); //rejects the promise with `error` as the reason
    }
    else
    {
      //Verify endpoint returns 200 (OK) response code.
      assert.ok(response.statusCode == 200, 'Expected 200 OK response, actual:' + response.statusCode);
      deferred.resolve(body); //fulfills the promise with body as the value
    }    
  });
  return deferred.promise; //promise is returned
};

var extractSecurityToken = function(data){
  log("Extracting Security Token");
  var deferred = Q.defer();
  //Parse JSON received from Insights into variable.
  var info = JSON.parse(data);
  log("Security token retrieved successfully");
  deferred.resolve(info.access_token);
  return deferred.promise;
};

var buildApiOptions = function(securityToken){
  var deferred = Q.defer();
  log("Building API options");
  // build your api options here
  var options = {
    //Define endpoint URL.
    //url: "https://webhook.site/ddb04be2-8961-4771-b934-6dddfa40ab57",
    url: "http://url.com",
    //Define body of PATCH request.
    headers: {'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + securityToken},
    body: {
      "Description": "fooba3r"
    },
    json: true

  };
  deferred.resolve(options); //fulfills the promise with options as the value
  return deferred.promise; //promise is returned
};

var makeApiCall = function(options){
  var deferred = Q.defer();
  log("Making API call");

  //Make PATCH request, passing in options and callback.
  $http.patch(options, function(error, response, body){
    if (error)
    {
      log(error);
      deferred.reject(error); //rejects the promise with `error` as the reason
    }
    else
    {
      //Verify endpoint returns 204 (No Content) response code.
      assert.ok(response.statusCode == 204, 'Expected 204 OK response, actual:' + response.statusCode);
      deferred.resolve(body); //fulfills the promise with body as the value
    }
  });
  return deferred.promise; //promise is returned
};

var validateApiCall = function(body){
  log("Validating Api Call");
  var deferred = Q.defer();
  //Parse JSON received from Insights into variable.
  //var info = JSON.parse(body);
  //assert.ok(shouldDisplayError(info.ErrorMessage), "Error Message: " + info.ErrorMessage);
	
  // perform any other validation here
  log("Completed successfully");
  deferred.resolve();
  return deferred.promise;
};

checkInMaintenanceWindow("Friday", "00:00", "01:30")
.then(function(){
  return buildSecurityOptions()
  .then(getSecurityToken)
  .then(extractSecurityToken)
  .then(buildApiOptions)
  .then(makeApiCall)
  .then(validateApiCall);
},
function(message){
  if(message != MaintenanceMessage)
  {
    throw new Error(MaintenanceMessage);
  }
  else
  {
    log(message);
  }
})
.done();
//Import the `assert` module to validate results.
var assert = require('assert');

var options = {
    url: "https://some_url.com",
        "headers": {
          "oauth_clientid": 123,
          
          },
        //"timeout": 15000
        };

$http.get(options, function(error, response, body) {
    console.log(response.statusCode + " status code")
    assert.ok(response.statusCode == 401, 'Expected 401 OK response');  
      });
sudo forever start --sourceDir /opt/bitnami/projects/nesk_back -c "npm run prod" /
var readline = require("readline");
var rl = readline.createInterface({input: process.stdin, output: process.stdout});

var program = function(){
    rl.question("type question", function(answer) {
        switch (answer){
            case "option 1":
                //action 1;
                break;
            case "exit option":
            	//previous action
            	return rl.close();
            default:
                //default action
        }
        program();
    });
}

program();
app.get('/:id/tracker.png', function(request, response, next) {
    var emailId = request.param.id;
    var buf = new Buffer([
        0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00,
        0x80, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x2c,
        0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
        0x02, 0x44, 0x01, 0x00, 0x3b
    ]);
    response.set('Content-Type', 'image/png');
    response.end(buf, 'binary');
    db.findOne({ id: emailId }, function(error, email) {
        if(error) return next(error);
        app.emit('event:opened', email);
    });
});

app.on('event:opened', function(email) {
    console.log('Email was opened');
    console.log(email.to);
    console.log(email.subject);
});
The following examples illustrate defining simple routes.

Respond with Hello World! on the homepage:
//get method for retrieving data.
app.get('/', function (req, res) {
  res.send('Hello World!')
})
 Save
Respond to POST request on the root route (/), the application’s home page:
//send method for sending data.
app.post('/', function (req, res) {
  res.send('Got a POST request')
})
 Save
Respond to a PUT request to the /user route:
//put request to 
app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user')
})
 Save
Respond to a DELETE request to the /user route:

app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at /user')
})
Basic routing
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one or more handler functions, which are executed when the route is matched.

Route definition takes the following structure:

app.METHOD(PATH, HANDLER)
 Save
Where:

app is an instance of express.
METHOD is an HTTP request method, in lowercase.
PATH is a path on the server.
HANDLER is the function executed when the route is matched.
function processSQLFile(fileName) {

  // Extract SQL queries from files. Assumes no ';' in the fileNames
  var queries = fs.readFileSync(fileName).toString()
    .replace(/(\r\n|\n|\r)/gm," ") // remove newlines
    .replace(/\s+/g, ' ') // excess white space
    .split(";") // split into all statements
    .map(Function.prototype.call, String.prototype.trim)
    .filter(function(el) {return el.length != 0}); // remove any empty ones

  // Execute each SQL query sequentially
  queries.forEach(function(query) {
    batch.push(function(done) {
      if (query.indexOf("COPY") === 0) { // COPY - needs special treatment
        var regexp = /COPY\ (.*)\ FROM\ (.*)\ DELIMITERS/gmi;
        var matches = regexp.exec(query);
        var table = matches[1];
        var fileName = matches[2];
        var copyString = "COPY " + table + " FROM STDIN DELIMITERS ',' CSV HEADER";
        var stream = client.copyFrom(copyString);
        stream.on('close', function () {
          done();
        });
        var csvFile = __dirname + '/' + fileName;
        var str = fs.readFileSync(csvFile);
        stream.write(str);
        stream.end();
      } else { // Other queries don't need special treatment
        client.query(query, function(result) {
          done();
        });
      }
    });
  });
}
const port = process.env.PORT || 3000;

import express from "express";
import path from "path";
import bodyParser from "body-parser";
import cors from "cors";
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());

//* Root Handler
app.get("/", (req, res) =>
  res.sendFile(path.join(__dirname + "/public/index.html"))
);

app.get('api/v1', (req,res) => res.json())

// Set static folder
app.use(express.static(path.join(__dirname, 'public')));

app.use('/api/v1', require('./routes/api/v1'))

app.listen(port, () => {
  console.log(`Server at: http://localhost:${port}`);
});
command line

npm init -y (creates the package for dependencies)

npm i [module]  (creates dependency key and module repository)
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "attach",
      // "processId": "${command:PickProcess}",
      "protocol": "inspector",
      "restart": true,
      "name": "Launch Programa",
      "skipFiles": ["<node_internals>/**"]
    }
  ]
}
// BASH
mkdir src
mkdir build
touch src/index.ts
touch .gitignore
touch README.md
tsc -y
npm init -y
npm install nodemon concurrently @types/express --save-dev

// package.json
...
"scripts": {
  "start:build": "tsc -w",
  "start:run": "nodemon ./build/index.js",
  "start": "concurrently npm:start:*"
},
...

// tsconfig.json
...
"outDir": "./build",
"rootDir": "./src",
...

// .gitignore
node_modules
*.env

// README.md
### Start
```bash
npm run start
```

// src/index.ts
import express from 'express'
const port = 3000
const app = express()

console.log("Hello, World!!!")

logSomething("This is a string that I'm logging")

app.listen(port, () => {
  console.log(`Listening on port ${port}`)
})
const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname, '/pictures');

fs.mkdirSync(dirPath);
router.post("/user", async (req, res) => {
  try {
    var user = new User(req.body);
    await user.save();
    res.status(200).send(user);
  } catch (error) {
    if (error.name === "ValidationError") {
      let errors = {};

      Object.keys(error.errors).forEach((key) => {
        errors[key] = error.errors[key].message;
      });

      return res.status(400).send(errors);
    }
    res.status(500).send("Something went wrong");
  }
});
const express = require('express')
const { graphqlHTTP } = require("express-graphql");
const {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
  GraphQLList,
  GraphQLInt,
  GraphQLNonNull
} = require('graphql')
const app = express()
const port = 3000

// Sample Data
const authors = [
	{ id: 1, name: 'Dan Brown' },
	{ id: 2, name: 'J. R. R. Tolkien' },
	{ id: 3, name: 'Brent Weeks' }
]

const books = [
	{ id: 1, name: 'The Lost Symbol', authorId: 1 },
	{ id: 2, name: 'Angels and Demons', authorId: 1 },
	{ id: 3, name: 'The Davinci Code', authorId: 1 },
	{ id: 4, name: 'The Fellowship of the Ring', authorId: 2 },
	{ id: 5, name: 'The Two Towers', authorId: 2 },
	{ id: 6, name: 'The Return of the King', authorId: 2 },
	{ id: 7, name: 'The Way of Shadows', authorId: 3 },
	{ id: 8, name: 'Beyond the Shadows', authorId: 3 }
]

const BookType = new GraphQLObjectType({
  name: 'Book',
  description: 'This represents a book written by an author',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) },
    authorId: { type: GraphQLNonNull(GraphQLInt) },
    author: {
      type: AuthorType, // AuthorType is defined below the same way that BookType is defined above
      resolve: (book) => {
        return authors.find(author => author.id === book.authorId)
      }
    }
  })
})

const AuthorType = new GraphQLObjectType({
  name: 'Author',
  description: 'This represents the author of a book',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) }
  })
})

const RootQueryType = new GraphQLObjectType({
  name: 'Query',
  description: 'Root Query',
  fields: () => ({
    books: {
      type: new GraphQLList(BookType),
      description: "List of books",
      resolve: () => books
    }
  })
})

const schema = new GraphQLSchema({
  query: RootQueryType
})



app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true
}))


app.get('/', (req, res) => {
  res.send(`<a href="http://localhost:${port}/graphql">GraphiQL</a>`)
})

// QUERY:
// 
// {
// 	books {
//     id
//   	name
//     author {
//       name
//     }
// 	}
// }

// RESULT
// 
// {
//   "data": {
//     "books": [
//       {
//         "id": 1,
//         "name": "The Lost Symbol",
//         "author": {
//           "name": "Dan Brown"
//         }
//       },
//       {
//         "id": 2,
//         "name": "Angels and Demons",
//         "author": {
//           "name": "Dan Brown"
//         }
//       }, //...
//     ]
//   }
// }

app.listen(port, () => {
  console.log(`App listening on http://localhost:${port}`)
});
$ sudo npm install --global cross-env
var express = require('express');
var app = express();

app.enable('trust proxy'); //to detect if req.secure is true/false

//Block http requests. Only allow https requests
app.use(function (req, res, next) {
	if (req.headers['x-forwarded-proto'] !== 'https'){
      return res.status(404).send('Not found');
    } else {
    next();
    }
})

exports = module.exports = app;
router.get("/search/:page", (req, res, next) => {
  const resultsPerPage = 5;
  const page = req.params.page >= 1 ? req.params.page : 1;
  const query = req.query.search;

  Product.find({ name: query })
    .select("name")
    .sort({ name: "asc" })
    .limit(resultsPerPage)
    .skip(resultsPerPage * page)
    .then((results) => {
      return res.status(200).send(results);
    })
    .catch((err) => {
      return res.status(500).send(err);
    });
});
userSchema.pre('save', async function(next){
    if (!this.isModified('password')) return next()
    this.password = await bcrypt.hash(this.password, 8)

    next()
})
//You must require fs and path before this action can be done
//set this on the top of the model
const imagePath = 'uploads/image'


//Create a virtual with the schema name e.g.
blogSchema.virual('imagePath').get(function(){
if(this.image != null){
return path.join('/', imagePath, this.image)
}
})

//exports the imagePath as like this
module.exports.imagePath = imagePath 


//go to the route and require it with the model name e.g.
const uploadPath = path.join("public", BlogModel.imagePath);

//set your function for unlink and call it on the delete route
function removeImage(image){
	fs.unlink(uploadPath, image), (err)=>{
    if(err) console.log(err)
    })
}

// Let generalize user data
app.use((req, res, next) => {
    res.locals.user = req.isAuthenticated() ? req.user : null
    return next()
})
const passport = require('passport')
const LocalStrategy = require("passport-local").Strategy;

passport.use(new LocalStrategy({
    usernameField: 'email'
}, async (email, password, done)=>{
    try{    
    const user = await User.findOne({ email })
        if (!user) return done(null, false, { message: 'User not exists' })
        if (!await user.checkPassword(password)) return done(null, false, { message: 'Incorrect Password' })
        return done(null, user)
    } catch (e) {
        
        return done(e)
    }
}
))

passport.serializeUser((user, done)=>{
    return done(null, user._id)
})

passport.deserializeUser(async (_id, done) => {
    try {
        const user = await User.findOne({ _id })
        return done(null, user)
    } catch (e) {
        return done(e)
    }
})





//place this one on the route
router.post('/login', (req, res, next) => {
  console.log(req.body.email)
  passport.authenticate('local', (err, user, info) => {
    if (err) {
      req.session.flashData = {
        message: {
          type: 'error',
          body: 'Login failed'
          }
      }
      return res.redirect('/user/login')
      }
    // Let check for user
    if (!user) {
      req.session.flashData = {
        message: {
          type: 'error',
          body: info.message
        }
      }
      return res.redirect('/user/login')
    }
    req.logIn(user, (err) => {
      if (err) {
        req.session.flashData = {
          message: {
            type: 'error',
            body: 'Login failed'
          }
        }
      }
      return res.redirect('/task/viewtask')
    })
  })(req, res, next)
})


//place this on index.js

// For Passport to work with session
app.use(passport.initialize());
app.use(passport.session());
const flashMsg = (req, res, next) => {
    if (req.session.flashData) {
        for (const key in req.session.flashData) {
            res.locals[key] = req.session.flashData[key]
        }

        req.session.flashData = null
    }
     
    next()
}

module.exports = flashMsg
const mongooseValidation = (theError) => {
    const errors = {}
    const details = errors.theError
    for (const key in details)
    {
        errors[key] = [details[key].message]
    }
    return errors
}

module.exports = mongooseValidation
var {src, dest, watch}        = require('gulp');
var browserSync = require('browser-sync').create();
var sass        = require('gulp-sass');

// Static server
  function bs() {
    serveSass();
  browserSync.init({
      server: {
          baseDir: "./"
      }
  });
  watch("./*.html").on('change', browserSync.reload);
  watch("./scss/**/*.scss", serveSass);
  watch("./js/*.js").on('change', browserSync.reload);
};

// Compile sass into CSS & auto-inject into browsers
 function serveSass() {
  return src("./scss/*.scss")
      .pipe(sass())
      .pipe(dest("./css"))
      .pipe(browserSync.stream());
};

exports.serve = bs;
var fs = require('fs');

fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));
var stripe = require('stripe')('sk_test_LIPsyf7cwBv0pbWPbzjeqAhj009wgDByN7');

stripe.customers.create(
  {
    description: 'My First Test Customer (created for API docs)',
  },
  function(err, customer) {
    // asynchronously called
  }
);
var express = require("express");
var app = express();
const session = require('express-session');
var MemcachedStore = require('connect-memjs')(session);

// configure sessions
var store = new MemcachedStore({servers: [process.env.MEMCACHEDCLOUD_SERVERS], username: process.env.MEMCACHEDCLOUD_USERNAME, password: process.env.MEMCACHEDCLOUD_PASSWORD});
app.use(session({ secret: 'keyboard cat',
   resave: true,
   saveUninitialized: true,
   cookie: { secure: true }, 
   store: store
}))
                                exports.removeById = (req, res) => {
   UserModel.removeById(req.params.userId)
       .then((result)=>{
           res.status(204).send({});
       });
};

                                
                                var app = express()
var sess = {
  secret: 'keyboard cat',
  cookie: {}
}
 
if (app.get('env') === 'production') {
  app.set('trust proxy', 1) // trust first proxy
  sess.cookie.secure = true // serve secure cookies
}
 
app.use(session(sess))
                                
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: function (result) {
       alert("The result is "+result);
	}
});
                                
<form action="/new" method="post">

  <input name="title" type="text">
  <input name="description" type="text">
  <input name="steps[0][text]" type="text">
  <input name="steps[0][ingredients]" type="text">
  <input name="steps[1][text]" type="text">
  <input name="steps[1][ingredients]" type="text">
  <button type="submit">Submit Form</button>

</form>
const songs[];
const results;

for (var i, i++, i<songs.length){
    if(song[i].artist == "Drake"){
      result.push(songs[i]);
    };

// OR

const songs [];
const result = songs.filter ( song => song.artist == "Drake");
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var slug = require('mongoose-slug-generator');

mongoose.plugin(slug);

const pageSchema = new Schema({
    title: { type: String , required: true},
    slug: { type: String, slug: "title" }
});

var Page = mongoose.model('Page', pageSchema);
module.exports = Page;
router.post('/:id/edit', auth.requireLogin, (req, res, next) => {
  Post.findByIdAndUpdate(req.params.id, req.body, function(err, post) {
    if(err) { console.error(err) };

     res.redirect(`/`+req.params.id);
  });
});
$ git status 
$ git add .
$ git commit -m "update information"
$ git push heroku master
$ git heroku open
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const exampleSchema = new Schema({
    title: { type: String , required: true},
    content: [{type: String}]
});


var Example = mongoose.model('Example', exampleSchema);
module.exports = Example;
> More steps
db.students.update(
   { _id: 1 },
   { $push: { scores: 89 } }
)
<form action="/new" method="post">
 
  <input name="title" type="text">
  <input name="description" type="text">
  <button type="submit">Submit Form</button>
 
</form>
> More steps
star

Thu Jul 15 2021 09:01:12 GMT+0000 (UTC)

#mongodb #mongoose #nodejs
star

Mon Jul 05 2021 11:17:27 GMT+0000 (UTC) https://dev.to/kowalevski/how-to-install-or-update-node-by-using-nvm-node-version-manager-1ip1

#javascript #nodejs #nvm #npm
star

Mon Jun 14 2021 12:11:52 GMT+0000 (UTC)

#heroku #nodejs #commandline
star

Mon Jun 07 2021 08:25:51 GMT+0000 (UTC)

#hbs #handlebars #express #nodejs
star

Sun Jun 06 2021 15:47:09 GMT+0000 (UTC) https://attacomsian.com/blog/nodejs-password-hashing-with-bcrypt

#bcrypt #authentication #express #nodejs #password
star

Sun Jun 06 2021 15:41:09 GMT+0000 (UTC) https://attacomsian.com/blog/mongoose-connect-async-await

#mongoose #mongodb #nodejs
star

Sun May 23 2021 14:30:42 GMT+0000 (UTC)

#nodejs #heroku #github
star

Fri May 21 2021 20:09:05 GMT+0000 (UTC)

#html #nodejs #pdf
star

Sat May 08 2021 17:59:57 GMT+0000 (UTC)

#jest #nodejs #testing
star

Sat May 08 2021 07:38:30 GMT+0000 (UTC)

#javascript #nodejs
star

Tue Apr 27 2021 22:51:13 GMT+0000 (UTC) wrote it myself

#nodejs
star

Wed Apr 21 2021 09:13:13 GMT+0000 (UTC)

#nodejs
star

Wed Mar 31 2021 12:07:26 GMT+0000 (UTC)

#nodejs #mongoose
star

Mon Mar 15 2021 13:40:38 GMT+0000 (UTC) https://github.com/mattdesl/gsx-pdf-optimize

#nodejs #commandline #npx
star

Thu Mar 11 2021 13:05:11 GMT+0000 (UTC)

#nodejs
star

Tue Mar 09 2021 15:29:16 GMT+0000 (UTC)

#nodejs
star

Wed Feb 24 2021 20:46:20 GMT+0000 (UTC) https://www.npmjs.com/package/ip

#nodejs #javascript
star

Sat Feb 06 2021 12:27:05 GMT+0000 (UTC)

#javascript #nodejs
star

Thu Jan 07 2021 22:05:21 GMT+0000 (UTC) https://www.reddit.com/r/node/comments/4txqqw/how_to_track_email_opens_with_nodejs_app/

#nodejs #javascript #email
star

Fri Dec 04 2020 01:43:47 GMT+0000 (UTC)

#nodejs,jquery #nodejs
star

Fri Dec 04 2020 01:42:13 GMT+0000 (UTC)

#nodejs #jquery
star

Fri Nov 27 2020 18:42:18 GMT+0000 (UTC) https://stackoverflow.com/questions/22636388/import-sql-file-in-node-js-and-execute-against-postgresql

#sql #nodejs
star

Sun Nov 22 2020 16:49:47 GMT+0000 (UTC) debtcollect.io

#typescript #nodejs
star

Sat Nov 14 2020 17:51:41 GMT+0000 (UTC)

#nodejs
star

Wed Nov 11 2020 12:56:36 GMT+0000 (UTC)

#json #nodejs #debug
star

Wed Nov 04 2020 18:12:52 GMT+0000 (UTC) https://www.digitalocean.com/community/tutorials/nodejs-how-to-use__dirname

#javascript #nodejs
star

Sat Oct 10 2020 17:41:42 GMT+0000 (UTC) https://stackoverflow.com/questions/61056021/improve-mongoose-validation-error-handling

#javascript #nodejs #mongoose
star

Fri Oct 09 2020 23:22:52 GMT+0000 (UTC) https://github.com/716green/graphql-express-setup/blob/main/server.js

#nodejs #javascript #graphql #express
star

Sun Oct 04 2020 06:48:54 GMT+0000 (UTC)

#nodejs
star

Wed Aug 26 2020 21:29:30 GMT+0000 (UTC)

#nodejs #javascript
star

Sat Aug 22 2020 23:06:10 GMT+0000 (UTC)

#nodejs #javascript
star

Mon Aug 17 2020 16:22:15 GMT+0000 (UTC)

#nodejs #javascript
star

Mon Aug 17 2020 16:18:23 GMT+0000 (UTC)

#nodejs #javascript
star

Mon Aug 17 2020 15:53:41 GMT+0000 (UTC)

#nodejs #javascript
star

Mon Aug 17 2020 15:51:22 GMT+0000 (UTC)

#nodejs #javascript
star

Tue Aug 04 2020 22:56:30 GMT+0000 (UTC) https://flaviocopes.com/node-mass-rename-files/

#javascript #nodejs
star

Mon Jun 29 2020 22:48:29 GMT+0000 (UTC)

#gulp #nodejs
star

Mon Jun 08 2020 10:15:25 GMT+0000 (UTC) https://lavalite.org/blog/fastest-method-to-copy-file-in-nodejs

#nodejs #fs #javascript
star

Mon May 25 2020 10:06:38 GMT+0000 (UTC) https://stripe.com/docs/api/customers/create

#nodejs
star

Thu Apr 30 2020 06:35:49 GMT+0000 (UTC) https://www.toptal.com/nodejs/secure-rest-api-in-nodejs

#nodejs
star

Tue Apr 28 2020 19:40:32 GMT+0000 (UTC) https://medium.com/javascript-in-plain-english/querying-sql-server-in-node-js-using-async-await-5cb68acf2144

#javascript #nodejs
star

Tue Apr 28 2020 19:22:18 GMT+0000 (UTC) https://www.npmjs.com/package/express-session

#nodejs
star

Sun Apr 26 2020 20:50:22 GMT+0000 (UTC) https://api.jquery.com/jquery.post/

#javascript #nodejs
star

Sun Mar 29 2020 07:06:35 GMT+0000 (UTC) https://gist.github.com/trantorLiu/5924389

#javascript #nodejs #handlebars #express
star

https://docs.mongodb.com/manual/reference/operator/update/push/

#javascript #nodejs
star

https://medium.com/@thiscodeworks.com/how-to-redirect-your-node-js-app-hosted-on-heroku-from-http-to-https-50ef80130bff

#javascript #nodejs #commandline

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension