Snippets Collections
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);
	}
});
                                
db.students.update(
   { _id: 1 },
   { $push: { scores: 89 } }
)
<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>
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;
$ git status 
$ git add .
$ git commit -m "update information"
$ git push heroku master
$ git heroku open
<form action="/new" method="post">
 
  <input name="title" type="text">
  <input name="description" type="text">
  <button type="submit">Submit Form</button>
 
</form>
> More steps
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;

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


var Example = mongoose.model('Example', exampleSchema);
module.exports = Example;
> More steps
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);
  });
});
bookmark
dashboard

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

#typescript #nodejs
bookmark
dashboard

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

#nodejs
bookmark
dashboard

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

#json #nodejs #debug
bookmark
dashboard

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

#javascript #nodejs
bookmark
dashboard

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

#javascript #nodejs #mongoose
bookmark
dashboard

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
bookmark
dashboard

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

#nodejs
bookmark
dashboard

Sat Sep 26 2020 11:03:32 GMT+0000 (UTC)

#nodejs #express #heroku
bookmark
dashboard

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

#nodejs #javascript
bookmark
dashboard

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

#nodejs #javascript
bookmark
dashboard

Tue Aug 18 2020 16:27:50 GMT+0000 (UTC)

#javascript #nodejs
bookmark
dashboard

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

#nodejs #javascript
bookmark
dashboard

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

#nodejs #javascript
bookmark
dashboard

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

#nodejs #javascript
bookmark
dashboard

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

#nodejs #javascript
bookmark
dashboard

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

#javascript #nodejs
bookmark
dashboard

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

#gulp #nodejs
bookmark
dashboard

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

#nodejs #fs #javascript
bookmark
dashboard

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

#nodejs
bookmark
dashboard

Fri May 08 2020 23:05:13 GMT+0000 (UTC)

#nodejs
bookmark
dashboard

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

#nodejs
bookmark
dashboard

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
bookmark
dashboard

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

#nodejs
bookmark
dashboard

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

#javascript #nodejs
bookmark
dashboard

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

#javascript #nodejs #handlebars #express
bookmark
dashboard

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

#javascript #nodejs

.

bookmark
dashboard
bookmark
dashboard

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