In JavaScript, you can output colored logs to the console using the %c directive in console.log(). Here’s an example:
1
console.log("%cThis is a green text", "color:green; font-size: 18px");
output: In this example, %c is used as a placeholder for the styles that are specified in the second argument. The text “This is a green text” will be displayed in green color in the console.
You can also specify multiple styles:
1
console.log("%cThis is a blue text on yellow background", "color:blue; background-color:yellow");
output:
In this example, the text will be blue and the background color will be yellow.
console.dir()
To print a deeply nested object in a more readable way, you can use console.dir().
Usually, we resolve this by using JSON.stringify() to convert the object to a string.
1
console.log(JSON.stringify(obj));
but this method has a limitation: it only works for objects that are serializable to JSON. If the object contains circular references, it will throw an error.
Posted onEdited onInjavascript Symbols count in article: 373Reading time ≈1 mins.
JavaScript flatMap
flatMap is the combination of map and flat, It first maps each element using a mapping function, then flattens(only one level) the result into a new array. It’s the same as map followed by flat.
So, When to use flatMap? When using Array.prototype.map the callback function usually return an element, but sometimes it returns an array, and you want to flatten the result. Then you can use flatMap to make the code more concise and readable.
Posted onEdited onInsecurity Symbols count in article: 382Reading time ≈1 mins.
Authentication vs Authorization
Authentication and authorization are two closely related concepts, but they are not the same. They are both used to protect resources, but they do so in different ways.
In simple terms, authentication is the process of verifying who a user is, while authorization is the process of verifying what they have access to.
Comparing these processes to a real-world example, when you go through security in an airport, you show your ID to authenticate your identity. Then, when you arrive at the gate, you present your boarding pass to the flight attendant, so they can authorize you to board your flight and allow access to the plane.
Authentication
Authentication is the process of verifying the identity of a user. This is typically done by asking for a username and password, but it can also be done using other methods, such as biometric data or security tokens.
The goal of authentication is to ensure that the person accessing a resource is who they claim to be.
Authorization
Authorization is the process of verifying what a user has access to. This is typically done by checking the user’s permissions and comparing them to the resource they are trying to access.
// gets all longest strings functionlongestString(inputArray) { // initialize the longest string to first value let { length } = inputArray[0]; for (let i = 1; i < inputArray.length; i++) { // checks if current string is longer than current longest if (length < inputArray[i].length) { length = inputArray[i].length; } } // filters out any values not equal to the longest string const strs = inputArray.filter((word) => word.length === length);
app.get('/', (req, res) => { res.cookie('username', 'John Doe', { maxAge: 900000, httpOnly: true }); res.end('Cookie has been set'); });
app.listen(3000, () => { console.log('Server is running on port 3000'); });
In this example, res.cookie('username', 'John Doe', { maxAge: 900000, httpOnly: true }); sets a cookie named “username” with the value “John Doe”. The maxAge option sets the expiry time for the cookie in milliseconds. The httpOnly option is a security enhancement that restricts the cookie from being accessed by client-side scripts.
Get cookie by request header
In Node.js, you can use the request.headers.cookie property to get cookies from the client side. Here’s an example using the Express.js framework:
Note that the cookie value cannot contain semicolons, commas, or whitespace. For a solution, use the encodeURIComponent() function to encode the value.
Posted onEdited onInweb Symbols count in article: 176Reading time ≈1 mins.
Web API
REST - Representational State Transfer
SOAP - Simple Object Access Protocol
GraphQL - A query language for your API
difference between REST and SOAP
Feature
REST
SOAP
Protocol
Can use any protocol but typically uses HTTP/HTTPS
Uses HTTP, SMTP, TCP, and more
Standards
No official standard, uses HTTP methods (GET, POST, PUT, DELETE)
Official standard by W3C
Performance
Lightweight, less data overhead
Heavyweight, more data overhead due to XML usage
Message format
Can use multiple formats (JSON, XML, etc.)
Uses XML
Security
Uses web security standards
Uses WS-Security which is more robust
Transaction support
No official support
Official support
State management
Stateless
Stateful
说明:
SOAP by itself is a protocol, but it can use any protocol to transport its messages, REST is not a protocol, it typically uses HTTP/HTTPS.
REST is stateless which means each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.
asyncfunctioncopyFilesWithNumberedNames(sourceDir, targetDir) { try { // Create target directory if it does not exist await fs.mkdir(targetDir, { recursive: true });
// Get all files from the source directory const filesToCopy = awaitgetAllFiles(sourceDir);
// Copy each file with a new numbered name let fileNumber = 1; for (const file of filesToCopy) { const newFilename = `${fileNumber}${path.extname(file)}`; const targetPath = path.join(targetDir, newFilename); await fs.copyFile(file, targetPath); console.log(`Copied ${file} to ${targetPath}`); fileNumber++; }
console.log('All files have been copied successfully.'); } catch (err) { console.error('An error occurred:', err); } }
const sourceDirectory = 'xxx'; // Replace with your source directory path const targetDirectory = 'xxx'; // Replace with your target directory path