diff --git a/index.js b/index.js index bb97912..586c810 100644 --- a/index.js +++ b/index.js @@ -186,6 +186,18 @@ morgan.format('dev', function developmentFormatLine (tokens, req, res) { ? res.statusCode : undefined + // respect NO_COLOR environment variable (see https://no-color.org) + if ('NO_COLOR' in process.env) { + var fn = developmentFormatLine.nocolor + + if (!fn) { + fn = developmentFormatLine.nocolor = compile( + ':method :url :status :response-time ms - :res[content-length]') + } + + return fn(tokens, req, res) + } + // get status color var color = status >= 500 ? 31 // red : status >= 400 ? 33 // yellow @@ -194,7 +206,7 @@ morgan.format('dev', function developmentFormatLine (tokens, req, res) { : 0 // no color // get colored function - var fn = developmentFormatLine[color] + fn = developmentFormatLine[color] if (!fn) { // compile diff --git a/test/morgan.js b/test/morgan.js index 6557a2b..7668d70 100644 --- a/test/morgan.js +++ b/test/morgan.js @@ -1354,6 +1354,31 @@ describe('morgan()', function () { }) }) + describe('dev with NO_COLOR', function () { + it('should not use ANSI color codes', function (done) { + var cb = after(2, function (err, res, line) { + if (err) return done(err) + assert.strictEqual(line.indexOf('\x1b'), -1, 'should not contain ANSI escape codes') + assert.ok(/GET \/ 200/.test(line), 'should contain method, url, and status') + done() + }) + + var stream = createLineStream(function onLine (line) { + cb(null, null, line) + }) + + process.env.NO_COLOR = '' + var server = createServer('dev', { stream: stream }) + + request(server) + .get('/') + .expect(200, function (err, res) { + delete process.env.NO_COLOR + cb(err, res) + }) + }) + }) + describe('short', function () { it('should match expectations', function (done) { var cb = after(2, function (err, res, line) {