Skip to content

Commit

Permalink
docs: add examples for ttl commands
Browse files Browse the repository at this point in the history
  • Loading branch information
luin committed Mar 27, 2022
1 parent 8b19b96 commit d57960a
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ redis.set("mykey", "hello", "EX", 10);

See the `examples/` folder for more examples. For example:

* [TTL](examples/ttl.js)
* [Strings](examples/string.js)
* [Hashes](examples/hash.js)
* [Lists](examples/list.js)
Expand All @@ -163,6 +164,8 @@ See the `examples/` folder for more examples. For example:
* [Streams](examples/stream.js)
* [Redis Modules](examples/module.js) e.g. RedisJSON

All Redis commands are supported. See [the documentation](http://luin.github.io/ioredis/classes/default.html) for details.

## Connect to Redis

When a new `Redis` instance is created,
Expand Down
3 changes: 3 additions & 0 deletions examples/hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ async function main() {
await redis.hincrby("user-hash", "age", 1);
const newAge = await redis.hget("user-hash", "age");
console.log(newAge); // 21

await redis.hsetnx("user-hash", "age", 23);
console.log(await redis.hget("user-hash", "age")); // 21, as the field "age" already exists.
}

main();
30 changes: 30 additions & 0 deletions examples/ttl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const Redis = require("ioredis");
const redis = new Redis();

async function main() {
await redis.set("foo", "bar");
await redis.expire("foo", 10); // 10 seconds
console.log(await redis.ttl("foo")); // a number smaller or equal to 10

await redis.set("foo", "bar", "EX", 20);
console.log(await redis.ttl("foo")); // a number smaller or equal to 20

// expireat accepts unix time in seconds.
await redis.expireat("foo", Math.round(Date.now() / 1000) + 30);
console.log(await redis.ttl("foo")); // a number smaller or equal to 30

// "XX" and other options are available since Redis 7.0.
await redis.expireat("foo", Math.round(Date.now() / 1000) + 40, "XX");
console.log(await redis.ttl("foo")); // a number smaller or equal to 40

// expiretime is available since Redis 7.0.
console.log(new Date((await redis.expiretime("foo")) * 1000));

await redis.pexpire("foo", 10 * 1000); // unit is millisecond for pexpire.
console.log(await redis.ttl("foo")); // a number smaller or equal to 10

await redis.persist("foo"); // Remove the existing timeout on key "foo"
console.log(await redis.ttl("foo")); // -1
}

main();

0 comments on commit d57960a

Please sign in to comment.