Node.js

使用Node.js建立redis連線的相關設定

在Node.js環境下建立Redis連線

  1. 初始化Node.js

> npm init

2. 安裝相關套件

本教學所需基本套件:redis、express、dotenv、nodemon、typescript、ts-node

> npm i -D redis express dotenv nodemon typescript tslib ts-node 

-D 相當於--save-dev,設定成開發時期依賴的套件

3. 建立.env文件,設置express服務及redis client的端口(port)

.env
PORT = 4200;
REDIS_PORT = 6379

4. 確認package.json中scripts內容包含以下serve指令

package.json
{
    ...,
    "scripts": {
        "serve": "nodemon --exec ts-node ./src/index.ts"
     },
     ...
 }

5. 建立src/index.ts資料夾與文件,index.ts內容範本如下

本教學之TypeScript程式碼均可複製貼上到Command Example區塊中執行

index.ts
import * as dotenv from 'dotenv';
import express from 'express';
import * as redis from 'redis'

// env variable
dotenv.config();
const PORT = Number(process.env.PORT) || 4200;
const REDIS_HOST = process.env.REDIS_HOST || "127.0.0.1";
const REDIS_PORT = Number(process.env.REDIS_PORT) || 6379;

// create redis connection
const client = redis.createClient({
    port: REDIS_PORT, 
    host: REDIS_HOST
});
client.on('error', function (error) {
    console.error(error);
});


// =============== Command Example ===============




// ===============================================


// app listening
const app = express();
app.listen(PORT, () => {
    console.log(`App port :`, PORT);
    console.log(`Redis host :`, REDIS_HOST);
    console.log(`Redis port :`, REDIS_PORT);
});

6. 在Terminal中執行以下指令npm run serve,測試運行結果

> npm run serve
App port : 4200
Redis host : 127.0.0.1
Redis port : 6379

Last updated

Was this helpful?