2017/06/28

Monitor File Change And Execute Code

現在寫 PHP 的時候都會試著在 node.js 以及 shell script 上實現,所以會不斷的嘗試程式碼,每次要看執行結果都要下一次 command 也挺累的,寫了一隻 w.js 來監控這三種檔案的變動並帶入對應的呼叫方式來節省時間

此功能需安裝 watch,執行方法為 node w.js xxx.php

w.js
const watch = require('watch');
const { exec } = require('child_process');
const path = require('path');
const argvs = process.argv;
const target = argvs[2];
const fs = require('fs');
const commandMap = {
    sh: 'bash',
    php: 'php',
    js: 'node'
};

if (target === undefined) {
    console.log('Need file argument!');
    return;
}

if (!fs.existsSync(target)) {
    console.log(`${target} is not exists!`);
    return;
}

let ext = path.extname(target).replace(/\./g, '');

if (Object.keys(commandMap).indexOf(ext) === -1) {
    console.log(`${ext} is not legal!`);
    return;
}

console.log(`Start to watch "${target}"!`);

watch.createMonitor('./', (monitor) => {
    monitor.on('changed', (file) => {
        if (file === target) {
            exec(`clear; ${commandMap[ext]} ${file}`, (error, stdout, stderr) => {
                if (error) {
                    console.error(`exec error: ${error}`);
                    return;
                }

                console.log(stdout);
                console.log(stderr);
            });
        }
    });
});

實際使用畫面大概是這樣

w.js 示意圖

2017/06/27

Random String

公司有一個需求想要產生 unique id,雖然 PHP 有 uniqid 可以使用,但他最基本的長度是 13 個字元,所以決定自己刻一個利用 0-9、a-z 產生的亂數密碼,會有 PHP、nodejs 以及 shell script 版本。

PHP
<?php

function code($length = 10)
{
    $codeString = '0123456789abcdefghijklmnopqrstubwxyz';
    $codeStringSplit = str_split($codeString);
    $codeStringSize = count($codeStringSplit);
    $code = '';

    for ($i = 0; $i < $length; ++$i) {
        $rand = mt_rand(0, $codeStringSize - 1);
        $code .= $codeStringSplit[$rand];
    }

    return $code;
}

for ($i = 0; $i < 10; $i++) {
    echo code().PHP_EOL;
}
node.js
function code(length) {
    var stringLength = length || 10;
    var codeString = '0123456789abcdefghijklmnopqrstubwxyz';
    var codeStringSplit = codeString.split('');
    var codeStringSize = codeStringSplit.length;
    var code = '';
    var min = 0;
    var max = codeStringSize - 1;

    for (var i = 0; i < stringLength; ++i) {
        var rand = Math.floor(Math.random() * (max - min + 1)) + min;

        code += codeStringSplit[rand];
    }

    return code;
}

for (var i = 0; i < 10; ++i) {
    console.log(code());
}
bash
#!/bin/bash

function code() {
    result=""
    length=10
    codeString="0123456789abcdefghijklmnopqrstubwxyz";
    declare -a array

    for (( i = 0; i < ${#codeString}; i++ )); do
        array+=(${codeString:$i:1})
    done

    if [[ -n $1 ]]; then
        declare -i length=$1
    fi

    max=$((${#array[@]} - 1))
    
    for (( i = 0; i < ${length}; i++ )); do
        rand=$(shuf -i 0-${max} -n 1)
        result="${result}${array[${rand}]}"
    done

    echo ${result}
}

for (( j = 0; j < 10; j++ )); do
    code
done