You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt.js 3中运行独立于客户端的Node.js后台脚本?

Solutions for Your Nuxt 3 Background Redis Sync Task

You’ve got two solid options here—integrating with Nuxt’s server layer or running a standalone script. Let’s break them down:

Option 1: Use a Nitro Plugin (Integrated Approach)

Since listen() only works in development, switch to a Nitro plugin—these run on server startup in both dev and production, and stay alive as long as your Nuxt server is running.

  1. Create a file at server/plugins/redis-sync.ts:
export default defineNitroPlugin(() => {
  const syncToRedis = async () => {
    try {
      // Replace this with your actual data query logic
      const freshData = await fetch('https://api.example.com/data').then(res => res.json());
      
      // Use unstorage to write to Redis
      const storage = useStorage('redis');
      await storage.setItem('app:cached-data', freshData);
    } catch (err) {
      console.error('Redis sync failed:', err);
    }
  };

  // Run once on server start
  syncToRedis();
  // Repeat every 3 seconds
  const interval = setInterval(syncToRedis, 3000);

  // Clean up interval when server shuts down
  process.on('SIGTERM', () => clearInterval(interval));
});
  • This activates automatically when you start Nuxt (dev or production builds).
  • Ensure your Redis setup is configured in nuxt.config.ts for unstorage (e.g., adding the Redis driver to your storage options).

Option 2: Standalone Node.js Script (Decoupled Approach)

If you don’t want the sync task tied to your Nuxt server’s lifecycle, a standalone script is simpler and more flexible.

  1. Create a file like redis-sync.js:
import { createStorage } from 'unstorage';
import redisDriver from 'unstorage/drivers/redis';

// Initialize Redis storage
const storage = createStorage({
  driver: redisDriver({ url: 'redis://localhost:6379' }) // Match your Redis config
});

const syncData = async () => {
  try {
    const freshData = await fetch('https://api.example.com/data').then(res => res.json());
    await storage.setItem('app:cached-data', freshData);
  } catch (err) {
    console.error('Sync error:', err);
  }
};

// Start the loop
syncData();
setInterval(syncData, 3000);
  1. Run it with Node:
node redis-sync.js

For production, use a process manager like pm2 to keep it running:

pm2 start redis-sync.js --name redis-sync

Which One to Pick?

  • Go with the Nitro plugin if your sync task relies on Nuxt environment variables, server-side utilities, or you want it to start/stop with your Nuxt app.
  • Choose the standalone script if you want full separation, easier debugging, or don’t want Nuxt restarts to interrupt the sync process.

内容的提问来源于stack exchange,提问作者Eugeny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:52:49