Nodemon-like task in Grunt : execute node process and watch

前端 未结 3 1416
执笔经年
执笔经年 2021-02-03 22:49

I feel like I\'m missing something.

Here is what I want to achieve :

Having a grunt task that executes my server.js and runs watch task

3条回答
  •  时光说笑
    2021-02-03 23:04

    Edit: grunt-nodemon

    since writing this, a nice person developed that.


    I was having a lot of trouble using grunt.util.spawn to fire off new processes. They would run, but they wouldn't give me any output back. Perhaps you can figure out what I could not in these docs. http://gruntjs.com/api/grunt.util#grunt.util.spawn

    Two problems I see with what you have:

    • I think grunt.registerTask() has to take three arguments when you use a callback function to run your task.
    • I don't think you can just call node server.js over and over again everytime a file changes. It will work on the first time, for it to really work you'd have to manage the server as a child process, killing and restarting it on subsequent file changes.

    For the registerTask arguments try this, just to see if you can get something to work in your current implementation.

    http://gruntjs.com/api/grunt.task#grunt.task.registertask

    It takes (taskName, description, taskFunction) like so:

    grunt.registerTask('start', 'My start task description', function() {
      grunt.util.spawn({
        cmd: 'node',
        args: ['server.js']
      });
      grunt.task.run('watch');
    });
    

    That might at least get your watch to run node server.js the first time a file changes.

    Here's what I would do instead.

    Either just use nodemon $ nodemon server.js as is

    or...

    Read the source and use grunt-develop

    He is managing the server as a child process, might be what you're looking for.

    or...

    Get grunt-shell
    npm install grunt-shell --save-dev

    And use it to run nodemon for you:

    module.exports = function(grunt) {
    
      // Project configuration.
      grunt.initConfig({
        serverFile: 'server.js',
        shell: {
          nodemon: {
            command: 'nodemon <%= serverFile %>',
            options: {
              stdout: true,
              stderr: true
            }
          }
        },
        watch: { /* nothing to do in watch anymore */ }
      });
    
      grunt.loadNpmTasks('grunt-contrib-watch');
      grunt.loadNpmTasks('grunt-shell');
    
      grunt.registerTask('default', 'shell:nodemon');
    };
    

    $ grunt shell:nodemon

    I sincerely hope that helps. Good luck!

提交回复
热议问题