使用Node.js读取Redis数据

程序

#! /usr/local/bin/node
// ---------------------------------------------------------------
//
//	redis_read.js
//
//						Mar/25/2023
// ---------------------------------------------------------------
'use strict'

const redis = require('redis')

// ---------------------------------------------------------------
async function read_proc()
{
//	const redisUrl = 'redis://127.0.0.1:6379'
//	const client = redis.createClient(redisUrl)
	const client = redis.createClient()

	await client.connect()

	const keys = await client.keys('*')

	for(var it in keys)
		{
		const key = keys[it]
		try
			{
			const value = await client.get(key)
			const data = JSON.parse(value)
			var out_str = key + "\t"
			out_str  += data.name + "\t"
			out_str += data.population + "\t"
			out_str += data.date_mod
			console.log (out_str)
			}
		catch (error)
			{
			console.error ("*** error *** from JSON.parse ***")
			console.error (error)
			console.error (key)
			}
		}
 
	await client.disconnect()
	console.error ("*** 終了 ***")
}

// ---------------------------------------------------------------
console.error ("*** 開始 ***")
read_proc()
// ---------------------------------------------------------------

运行结果

$ export NODE_PATH=/usr/local/lib/node_modules
$ ./redis_read.js
*** 開始 ***
t1859	坂井	25397	1950-11-9
t1858	越前	52486	1950-7-26
t1857	あわら	38251	1950-3-21
t1855	勝山	41358	1950-8-14
t1851	福井	92714	1950-9-12
t1853	小浜	67241	1950-10-2
t1852	敦賀	28158	1950-3-15
t1854	大野	32164	1950-6-22
t1856	鯖江	64792	1950-9-12
*** 終了 ***

确认的版本

$ node --version
v20.2.0

相关信息

Node.js: 创建 Redis 数据 (Create)
Node.js: 更新 Redis 数据 (Update)
Node.js: 删除 Redis 数据 (Delete)

bannerAds