Get to know each other

Console must be the most familiar partner of your front-end ER, whether it is console console, or console object, do front-end do for a long time, open a web page is always inexplable natural open console, some naughty websites will deliberately output some interesting things in the console, such as recruitment information, like Baidu:

Other do not say, really every year update, looking at it is very exciting.

It’s also common to output some fancy character graphics, such as Tmall’s:

There are also some sites that may not like to be debugged, as long as you open the console automatically into debug mode, or the kind of infinite debugger, the simplest implementation is as follows:

setInterval(() = >{
    debugger
}, 1000)
Copy the code

Crack is not difficult, interested can baidu.

I don’t know if there are people like me, do front-end for many years, rely on a console. Log world, as if console is a log method, if it is, then this article to further understand the console object.

To know each other

The console object is provided by the host environment, such as the browser and nodejs, as a property of the global object, which can be used directly without the constructor. The __proto__ of the console object refers to an empty object, so the methods of the console object are all attached to the object itself. Print the console in Chrome console to see the following methods or properties:

The console method can receive multiple arguments separated by commas, and will be printed on the same line without a newline. If you want a newline, use the console method to print multiple times.

In addition, the same method may differ in different browsers, since most of you are using Chrome, so the following content is mostly in Chrome effects.

It’s honestly boring to list the apis directly, so let’s look at the scenarios.

Scenario 1: Output normal debugging information, such as numbers, strings, objects, arrays, functions, and so on

You can use console.log or console.info, which are basically the same:

Scenario 2: You want to output different levels of debugging information, such as warning or error messages

Debugging level information can be displayed using the console.debug method. The console is not displayed by default. To see this information, check the corresponding option of the console:

Warning messages can be sent using the console.warn method, which adds a yellow background and an exclamation mark icon to the line and displays the stack information:

Error messages can be sent using the console.error method, which adds a red background and a cross icon to the line and displays the stack information:

Scenario 3: Want to see somethingDOMAll attributes of the element

For example, if I want to see all the attributes of the body element:

console.log(document.body)
Copy the code

In this case, the console prints out the DOM structure, not the properties:

To do that, we can use for in to iterate:

for(let p in document.body) {
    console.log(p, document.body[p])
}
Copy the code

Another easy way is to treat it as an item in an array or as a property value in an object:

console.log([document.body], {body:document.body})
Copy the code

Of course, none of this is the easiest. The easiest is to use the console.dir method directly:

Scenario 4: You want to see the specific call location, call stack, and so on

Log, INFO, error, etc. If you just need to find the call location, you can use console.assert, console.error, console.warn, and the specialized method console.trace. The trace method can take no arguments:

Scenario 5: SometimesconsoleYou write too much, you print out too much information, you can’t tell where it is at a glance, you can’t tell what’s related

This can be manually commented out except for what you need for this time. If you want to type a few more lines of code, you can also use the console.group method to display the group, and use the console.groupEnd method to end the group, which can be nested at multiple levels:

console.group(xxx)
xxx
console.groupEnd()
Copy the code

Fall in love

Scenario 1: Implement the above Baidu effect

Console uses \n to print newline characters:

console.log('Every planet has a driving core, \n the seeds of influence for every thought. \n Feel the temperature of the world, \n young you can be the power to change the world, \n Baidu values all your potential. N Your potential is the power to change the world! ')
Copy the code

Log (‘%x other characters ‘, ‘XXX ‘, [XXX, XXX…]) )

Set the style to the %c placeholder, you can use more than one, apply the style to the characters following the placeholder, and the rest of the arguments will print as normal after the placeholder is replaced:

console.log(%c Baidu 2021 Campus Recruitment Resume Delivery: '.'color:red'.'https://talent.baidu.com/external/baidu/campus.html')
Copy the code

Support for common style properties:

console.log(
    '% C Street % C Corner % C small % C forest '.'font-size: 20px; margin-right: 5px'.'color: #58A7F2'.'font-size: 24px; background: #F4605F; color: #fff; padding: 5px'.'border: 1px solid #8F4CFF; padding: 10px; border-radius: 50%'
)
Copy the code

In addition to %c, there are several other placeholders: % I, %f, %s, etc., which are not often used, so I won’t go into details.

Scene 2: Draw a dragon on the console

It seems that painting dragons is very popular recently, ok, meet you:

console.log('%c'.'background - image: url (/ dragon. JPG); background-size: 100%; padding:267px 300px; ')
Copy the code

Ps. It doesn’t work on Chrome for some reason, but this is what it looks like on Edge.

(Image is a fraud ah, and the image support is very poor, it is estimated that many browsers can not display, can change the way?)

Requirements are quite a lot, can not use pictures, that and the above Tmall cat with the same character to draw it for you, but so we need to first turn the picture into characters, the principle and the handsome that article, but the div into characters.

After using the canvas to get the pixel data of the picture, using two layers of nested loop and the outer traversal is high, the inner layer traversal wide, iteration is high when adding a newline \ n, iterative wide, according to the current pixel of r, g, b information judgment, or a null character is to add null character finally joining together to complete character is what we want to print characters, Because we need to note, however is a pixel corresponding to a character, but the actual size of the characters must be greater than one pixel, such as a 16 px text, so finally we get the characters of the graphics will be 16 times as much as the original image, it is too big, the console display, so you need to narrow, how to narrow, there are two methods, The second is to reduce sampling points. For example, we take a point every 10px. The problem is that the final image may be a little bit different from the original image.

// Load the image of the dragon
let img = new Image()
img.src = '/ dragon. JPG'
img.onload = () = > {
    draw()
}
// Draw the image to the canvas
const draw = () = > {
    const canvas = document.getElementById('canvas')
    canvas.width = img.width
    canvas.height = img.height
    const ctx = canvas.getContext('2d')
    ctx.drawImage(img, 0.0, img.width, img.height)
    // Get the pixel data
    const imgData = ctx.getImageData(0.0, img.width, img.height).data
    // Concatenation characters
    join(imgData)
}
// Concatenate the pixel data into characters
const join = (data) = > {
    let gap = 10
    let str = ' '
    for (let h = 0; h < img.height; h += gap) {
        str += '\n'
        for (let w = 0; w < img.width; w += gap) {
            str += ' '// Since the height of a character is generally larger than its width, an extra null character is added to balance it out, otherwise the final shape will feel stretched
            let pos = (h * img.width + w) * 4
            let r = data[pos]
            let g = data[pos + 1]
            let b = data[pos + 2]
            // Convert RGB to YUV format and determine what characters to display according to y (brightness)
            let y = r * 0.299 + g * 0.578 + b * 0.114
            if (y >= 190) {
                / / light color
                str += ' '
            } else {
                / / dark
                str += The '#'}}}console.log(str)
}
Copy the code

The effect is as follows:

As you can see, although we have the general shape, we have a lot less detail. There is another way to shrink the image and you can try it yourself. It might be a little better than this. But also need not bother, can be directly help you turn, there are many websites such as www.degraeve.com/img2txt.php.

Fall in love,

Scenario 1: How to print objects more easily

Object, we all know that it’s a reference type, so in our development, we often print an object or an array, and it’s fine if we don’t change it, but if we change it multiple times, and we want to see the data at this point after each change, unfortunately, Using methods such as console.log or dir will display the last data of the object:

let obj = {a: 1.b: [1.2.3]}
console.log(obj)
obj.a = 2
console.error(obj)
obj.b.push(4)
console.dir(obj)
Copy the code

You can see that there’s an exclamation mark next to it, and if you move it up, you’ll see a line that says: Evaluated This value was calculated upon first expanding,It may have changed since then. Console. log(json.stringify (obj)) or deep copy and print. Is there an easier way? We can add two methods to console, one called console.obj, which copies the object and prints it, and the other called console. STR, which serializes the object and prints it:

console.obj = function (. args) {
    let newArgs = args.map((item) = > {
        if (Object.prototype.toString.call(item) === '[object Object]' || Array.isArray(item)) {
            return deepClone(item)
        } else {
            return item
        }
    })
    console.log(... newArgs) }console.str = function (. args) {
    let newArgs = args.map((item) = > {
        try {
            let obj = JSON.stringify(item)
            return obj
        } catch(e) {
            return item
        }
    })
    console.log(... newArgs) }Copy the code

Scenario 2: How do I remove console in production

To remove the console object from the production environment, use the webpack plugin. You can also intercept the console object to determine if the production environment is in use. If it is, let’s override the console object.

let oldConsole = window.console
let newConsole = Object.create(null)
// Other methods are omitted here; ['log'].forEach((method) = > {
    newConsole[method] = function (. args) {
        // Non-development environments return directly
        if(process.env.NODE_ENV ! = ='development') {
            return} oldConsole[method](... args) } })window.console = newConsole
Copy the code

Rewriting console can be used in any scenario where you need to know about the console call, such as front-end monitoring log reporting.

Be together

The console in NodeJS is a little different from the browser, which is obvious, since the command line is certainly not as powerful as the browser:

As shown in the figure, the log, INFO, ERROR, WARN, and DEBUG methods appear to be indistinguished on the surface. Error and WARN do not have stack information as they do in the browser, trace remains the same, and printing objects is expanded directly. So the display that you want to format needs to do its own thing with the object that you want to print, such as for pure objects:

console.log(JSON.stringify({a: 1.b: [1.2.3]}, null.4))
Copy the code

In addition, the %c placeholder is obviously not effective, if you want to print out color can use chalk and other tools such as the library, other methods output effects if the command line does not support the console. Log will be processed directly.

The Console class does not exist in the browser environment, but it does exist in nodeJS. There are two ways to obtain it:

const { Console } = require('console')
const { Console } = console
Copy the code

Using the Console class, you can instantiate a new instance of Console by passing in the parameters you want:

/* stdout: writable stream, used to output information. Stderr: Optional writable stream, used to output error information. IgnoreErrors: Ignored errors when writing to the underlying stream */
new Console(stdout[, stderr][, ignoreErrors])
Copy the code

The default global console is output to the standard output and standard error streams, which is equivalent to:

new Console(process.stdout, process.stderr)
Copy the code

Then you can choose to output the log to the specified file:

const output = fs.createWriteStream('./stdout.log')
const errorOutput = fs.createWriteStream('./stderr.log')
new Console(output, errorOutput)
Copy the code

goodbye

Even if it is not give up, there will be parting, everyone see here the predestined people we meet next time ~