Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

node.js - What's the purpose of gruntjs server task?

I'm learning how to propel use gruntjs. I found the server task but I can't get the point.

Can i use the server task mapping concatenated/minified files to test my application (uses backbone.js) without moving or placing source files in web server root? Without apache for example.

If no, what's the supposed use of server task?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The server task is used to start a static server with the base path set as the web root.

Example: Serve ./web-root as http://localhost:8080/:

grunt.initConfig({
  server: {
    port: 8080,
    base: './web-root'
  }
});

It will function similar to an Apache server, serving up static files based on their path, but uses the http module via connect to set it up (source).

If you need it to serve more than just static files, then you'll want to consider defining a custom server task:

grunt.registerTask('server', 'Start a custom web server.', function() {
  grunt.log.writeln('Starting web server on port 1234.');
  require('./server.js').listen(1234);
});

And custom server instance:

// server.js
var http = require('http');
module.exports = http.createServer(function (req, res) {
    // ...
});

Can I use the server task mapping concatenated/minified files to test my application [...]

Concatenation and minification have their own dedicated tasks -- concat and min -- but could be used along with a server task to accomplish all 3.


Edit

If you want it to persist the server for a while (as well as grunt), you could define the task as asynchronous (with the server's 'close' event):

grunt.registerTask('server', 'Start a custom web server.', function() {
  var done = this.async();
  grunt.log.writeln('Starting web server on port 1234.');
  require('./server.js').listen(1234).on('close', done);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...