diff --git a/README.md b/README.md index 5c61bc78..9f4e5ebd 100644 --- a/README.md +++ b/README.md @@ -168,6 +168,10 @@ for information codes. GET /dev 200 0.224 ms - 2 ``` +Set the `NO_COLOR` environment variable to a non-empty value to disable the +colored output (see [no-color.org](https://no-color.org/)). The same fields are +then printed without any ANSI escape sequences. + ##### short Shorter than default, also including response time. diff --git a/index.js b/index.js index fc71056f..e31331f5 100644 --- a/index.js +++ b/index.js @@ -211,6 +211,15 @@ morgan.format('tiny', ':method :url :status :res[content-length] - :response-tim */ morgan.format('dev', function developmentFormatLine (tokens, req, res) { + // NO_COLOR (https://no-color.org/): when present and not an empty + // string, regardless of its value, ANSI color codes must not be added + if (process.env.NO_COLOR) { + var plainFn = developmentFormatLine.plain || (developmentFormatLine.plain = + compile(':method :url :status :response-time ms - :res[content-length]')) + + return plainFn(tokens, req, res) + } + // get the status code if response written var status = headersSent(res) ? res.statusCode diff --git a/test/morgan.js b/test/morgan.js index 08e4d16b..ce12c9bf 100644 --- a/test/morgan.js +++ b/test/morgan.js @@ -1523,6 +1523,38 @@ describe('morgan()', function () { .expect(200, cb) }) }) + + describe('with NO_COLOR environment variable set', function () { + beforeEach(function () { + process.env.NO_COLOR = '1' + }) + + afterEach(function () { + delete process.env.NO_COLOR + }) + + it('should not emit any ANSI escape codes', function (done) { + var cb = after(2, function (err, res, line) { + if (err) return done(err) + assert.strictEqual(line.indexOf('\x1b'), -1) + assert.ok(/^GET \/ 200 \d+\.\d{3} ms - -$/.test(line), 'unexpected line: ' + line) + done() + }) + + var stream = createLineStream(function onLine (line) { + cb(null, null, line) + }) + + var server = createServer('dev', { stream: stream }, function (req, res, next) { + res.statusCode = 200 + next() + }) + + request(server) + .get('/') + .expect(200, cb) + }) + }) }) describe('short', function () {