【问题标题】:node.js watch the folder and run scriptnode.js 监视文件夹并运行脚本
【发布时间】:2018-02-15 14:03:10
【问题描述】:

我是 node.js 的新手 在我的项目中,我使用 PM2 重新启动 node.js,它工作正常。

但是,我需要观察文件夹的变化,启动脚本而不是退出后重新启动它。

为简单起见,我将 yml 用于 I18n。 我的目标是,当我对 yml 文件进行更改时,运行脚本将其转换为 json,仅此而已。 等到 yml 文件有新的变化。

PM2 可以工作,但它会在每次运行后一次又一次地尝试重新启动脚本 退出。

PM2 |带有 id [1] 和 pid [28803] 的应用程序 [i18n compile],已退出 通过信号 [SIGINT] PM2 | 使用代码 [0]脚本 /home/.../src/i18n/convert.js 有太多不稳定的 重新启动 (16)。停了下来。 “错误”

我应该使用其他工具来解决这个问题吗?

【问题讨论】:

    标签: node.js pm2 nodemon


    【解决方案1】:

    我提醒自己,生活在异步环境中:

    1. 写了自己的观察者。
    2. 在主应用中为 PM2 ignore_watch 添加了语言环境目录。
    3. 将我的观察者添加为 PM2 应用,但只对观察者进行观察。

    {
      name         : 'I18n compiler',
      interpreter  : 'babel-node',
      script       : 'tools/locales.watcher.js',
      cwd          : path.root,
      watch        : 'tools/locales.watcher.js',
      ignore_watch : ['config', 'src', 'server', 'package.json'],
      env: {
        NODE_PATH: path.src,
        NODE_ENV: 'development'
      },
    }
    

    import fs      from 'fs';
    import config  from '../config/general';
    import convert from 'i18n/convert.js';
    
    const { path } = config;
    
     // Synchronous recursively list files in a directory
    function getFilesRecur(dir, filelist) {
      const files = fs.readdirSync(dir);
      filelist = filelist || [];
      files.forEach(function(file) {
        if (fs.statSync(path.join(dir, file)).isDirectory()) {
          filelist = getFilesRecur(path.join(dir, file), filelist);
        } else if ((/\.(yml|yaml)$/i).test(file)) {
          filelist.push(path.join(dir, file));
        }
      });
      return filelist;
    }
    
    export default function setupLocalesWatcher(){
      const files = getFilesRecur(path.i18n);
    
      files.forEach(function(file) {
        console.log(`Watching: ${file}`);
        fs.watchFile(file, () => {
          convert(file);
        });
      });
    
    }
    

    【讨论】:

      【解决方案2】:

      nodemon 是一个工具,可让您更改目录中的文件并自动运行脚本

      nodemon可以通过npm install -g nodemon安装

      script.js 或与script.js 位于同一目录中的任何其他文件发生更改时,执行nodemon script.js 将自动运行node script.js

      【讨论】:

      • 以及如何与 ES6 绑定? node_modules/.bin/babel-node node_modules/.bin/nodemon src/i18n/convert.js yarn babel-node -- nodemon src/i18n/convert.js yarn babel-node -- node_modules/.bin/nodemon src/i18n /convert.js SyntaxError: 意外的令牌导入
      • 如果您安装了更新版本的节点(iirc 节点 >= 7.6.0)es6 功能将起作用
      • 你能投票吗?你是说需要吗?你在用 babel 吗?
      • 是的,我使用 babel。
      • 传递给 nodemon 的参数将与传递给 node 以运行脚本的参数相同
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      • 2014-06-14
      相关资源
      最近更新 更多