Chủ Nhật, 5 tháng 2, 2017

Simple server side cache for Express.js with Node.js

'use strict'

var express = require('express');
var app = express();
var mcache = require('memory-cache');

app.set('view engine', 'jade');

var cache = (duration) => {
  return (req, res, next) => {
    let key = '__express__' + req.originalUrl || req.url
    let cachedBody = mcache.get(key)
    if (cachedBody) {
      res.send(cachedBody)
      return
    } else {
      res.sendResponse = res.send
      res.send = (body) => {
        mcache.put(key, body, duration * 1000);
        res.sendResponse(body)
      }
      next()
    }
  }
}

app.get('/', cache(10), (req, res) => {
  setTimeout(() => {
    res.render('index', { title: 'Hey', message: 'Hello there', date: new Date()})
  }, 5000) //setTimeout was used to simulate a slow processing request
})

app.get('/user/:id', cache(10), (req, res) => {
  setTimeout(() => {
    if (req.params.id == 1) {
      res.json({ id: 1, name: "John"})
    } else if (req.params.id == 2) {
      res.json({ id: 2, name: "Bob"})
    } else if (req.params.id == 3) {
      res.json({ id: 3, name: "Stuart"})
    }
  }, 3000) //setTimeout was used to simulate a slow processing request
})

app.use((req, res) => {
  res.status(404).send('') //not found
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})


Source: https://goenning.net/2016/02/10/simple-server-side-cache-for-expressjs/

ExpressJS middlewares async

So instead of:
app.use(getUser);
app.use(getSiteList);
app.use(getCurrentSite);
app.use(getSubscription);
… we could do something like this:
function parallel(middlewares) {
  return function (req, res, next) {
    async.each(middlewares, function (mw, cb) {
      mw(req, res, cb);
    }, next);
  };
}

app.use(parallel([
  getUser,
  getSiteList,
  getCurrentSite,
  getSubscription
]));

Thứ Hai, 12 tháng 12, 2016

FTP port

Here's the document I refer people to so that they can following the FTP protocol: http://slacksite.com/other/ftp.html
  • To do active-mode FTP, you need to allow incoming connections to TCP port 21 and outgoing connections from port 20.
  • To do passive-mode FTP, you need to allow incoming connections to TCP port 21 and incoming connections to a randomly-generated port on the server computer (necessitating using a conntrack module in netfilter)
You don't have anything re: your OUTPUT chain in your post, so I'll include that here, too. If your OUTPUT chain is default-drop then this matters.
Add these rules to your iptables configuration:
iptables -A INPUT -p tcp --dport 21 -j ACCEPT
iptables -A OUTPUT -p tcp --sport 20 -j ACCEPT
To support passive mode FTP, then, you need to load the ip_conntrack_ftp module on boot. Uncomment and modify the IPTABLES_MODULES line in the /etc/sysconfig/iptables-config file to read:
IPTABLES_MODULES="ip_conntrack_ftp"
Save the iptables config and restart iptables.
service iptables save
service iptables restart
To completely rule out VSFTPD as being a problem, stop VSFTPD, verify that it's not listening on port 21 with a "netstat -a" and then run a :
nc -l 21
This will start netcat listening on port 21 and will echo input to your shell. From another host, TELNET to port 21 of your server and verify that you get a TCP connection and that you see output in the shell when you type in the TELNET connection.
Finally, bring VSFTPD back up, verify that it is listening on port 21, and try to connect again. If the connection to netcat worked then your iptables rules are fine. If the connection to VSFTPD doesn't work after netcat does then something is wrong w/ your VSFTPD configuration.

Thứ Ba, 2 tháng 8, 2016

How to install MongoDB on Mac OS X

A guide to show you how to install MongoDB on Mac OS X.
  1. MongoDB 2.2.3
  2. Mac OS X 10.8.2

1. Download MongoDB

Get MongoDB from official website, extracts it :
Bash
$ cd ~/Download
$ tar xzf mongodb-osx-x86_64-2.2.3.tgz
$ sudo mv mongodb-osx-x86_64-2.2.3 /usr/local/mongodb

2. MongoDB Data

By default, MongoDB write/store data into the /data/db folder, you need to create this folder manually and assign proper permission.
Bash
$ sudo mkdir -p /data/db
$ whoami
mkyong
$ sudo chown mkyong /data/db
Note
Permissin is required to avoid following locking error :
Bash
Unable to create/open lock file: /data/db/mongod.lock

3. Add mongodb/bin to $PATH

Create a ~/.bash_profile file and assign /usr/local/mongodb/bin to $PATH environment variable, so that you can access Mongo’s commands easily.
Bash
$ cd ~
$ pwd
/Users/mkyong
$ touch .bash_profile
$ vim .bash_profile

export MONGO_PATH=/usr/local/mongodb
export PATH=$PATH:$MONGO_PATH/bin

##restart terminal

$ mongo -version
MongoDB shell version: 2.2.3

4. Start MongoDB

Start MongoDB with mongod and make a simple mongo connection with mongo.
Terminal 1
Bash
$ mongod
MongoDB starting : pid=34022 port=27017 dbpath=/data/db/ 64-bit host=mkyong.local
//...
waiting for connections on port 27017
Terminal 2
Bash
$ mongo
MongoDB shell version: 2.2.3
connecting to: test
> show dbs
local (empty)
Note
If you don’t like the default /data/db folder, just specify an alternate path with --dbpath
Bash
$ mongod --dbpath /any-directory

5. Auto Start MongoDB

To auto start mongoDB, create a launchd job on Mac.
Bash
$ sudo vim /Library/LaunchDaemons/mongodb.plist
Puts following content :
/Library/LaunchDaemons/mongodb.plist
Bash
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>mongodb</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/local/mongodb/bin/mongod</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>WorkingDirectory</key>
  <string>/usr/local/mongodb</string>
  <key>StandardErrorPath</key>
  <string>/var/log/mongodb/error.log</string>
  <key>StandardOutPath</key>
  <string>/var/log/mongodb/output.log</string>
</dict>
</plist>
Load above job.
Bash
$ sudo launchctl load /Library/LaunchDaemons/mongodb.plist

$ ps -ef | grep mongo
    0    71     1   0  1:50PM ??         0:22.26 /usr/local/mongodb/bin/mongod
  501   542   435   0  2:23PM ttys000    0:00.00 grep mongo
Try restart your Mac, MongoDB will be started automatically.

Source: http://www.mkyong.com/mongodb/how-to-install-mongodb-on-mac-os-x/

Thứ Sáu, 22 tháng 7, 2016

Linux command

5. tail -f 30 ~/.bash_history
7. cp -r test1 test2 test3/
8. mv f1 f2 d1/
10. mkdir -p /home/xxx/d1/d1/d1
14. ln -s d2/f2 d1/f1
15. chmod 500 /home/abc/d1
17. grep linhtd /etc/passwd
18. cat f1 f2 > f3
19. find /home/mai/staff -name "BTlinux*" -perm 750 -user huongtran
20. sort --help > f1
21. mkdir /home/tuananh;echo "" > /home/tuananh/readme.txt
22. find /home -iname "*.c" -size +1M
23. less: cho phép scoll up, down. more: chỉ có scoll down
24. ---x-w-r--
25. tar -cvjf dir1.bzip2 file1 file2
26. tar -tjf dir1.bzip2 >/dev/null
27. /etc/password. Username:Password:User ID (UID):Group ID (GID):User ID Info:Home directory:Command/shell:
23. umask 762
24. tar -cvzf dir1.tar.gz file1 file2
25. tar -xzf dir1.tar.gz
26. nohup exercise1 &
27. screen


Thứ Tư, 6 tháng 7, 2016