CSS Tips

Change css style of the parent element

e.g. change the parent background color if it contains the child class

1
2
3
.parent .child{
background-color: white;
}

History of web Front-end build tools

WEB前端为什么需要构建工具

WEB技术的发展和局限

TODO
C# dll: metadata, “data about data”

AJAX(gmail) - node.js 飞速发展期

当学习了一种前端技术的时候,同时会有几种新的前端技术诞生。

还有,你选择的那种前端技术,也许已经过时了。

前端构建工具的需求

预处理

JS/CSS/HTML在设计之初并未料及它们会这样流行,整个Web已经形成一个大的分布式文档。 低层语言的更换或升级都因兼容性问题而面临着巨大困难。 这催生了各种中间语言个预处理器,例如SASS,LESS,CoffeeScript,Babel等。
这些预处理工具可以将我们的中间代码转换为可运行的JavaScript。 这些预处理器使得我们可以预先使用ECMA Script6,以结构化的方式编写CSS,或者在CommonJS环境中编写JavaScript等等。

风格与测试

在一个典型的工作流中,每次Push主分支或npm发布都应首先运行代码风格检查和单元测试。 我们需要这些操作能够在合适的时候自动执行。

资源压缩

在开发网站代码时,我们希望模块化地进行编码。每个业务逻辑,通用工具,或者架构元素都需要组织在单独的文件中。 但是如果用户浏览网页时也载入这么多源文件,那么页面打开速度会大打折扣。
因此在网站发布时需要将源码合并压缩, JavaScript可能还会需要模块化(AMD,CommonJS等), CSS文件可能也需要合并、添加兼容性前缀(-webkit-, -moz-)等。 这些重复性工作我们也希望写成脚本。

自动刷新

监听本地源代码变化,自动重新构建、刷新浏览器。

静态资源替换

最为复杂的构建需求是静态资源的URL替换。 因为生产环境中的资源地址可能和开发环境中很不一样, 可能是由于JS合并、CSS合并,也可能是由于应用了CDN加速。
我们需要在部署时更改所有HTML文件中的静态资源地址。

模块合并

在采用模块化的项目里会有很多个模块和文件,需要通过构建功能将模块分类合并成一个文件。

自动发布

更新代码后,自动构建出线上发布代码并传输给发布系统。

构建其实是工程化、自动化思想在前端开发中的体现,将一系列流程用代码去实现,让代码自动化地执行这一系列复杂的流程。构建为前端开发注入了更大的活力,解放了我们的生产力。

前端构建工具的发展

历史上先后出现了一系列构建工具,他们各有优缺点。由于前端工程师很熟悉 JavaScript,Node.js 又可以胜任所有构建需求,所以大多数构建工具都是用 Node.js 开发的。

Npm Scripts

在 Npm Scripts 和 Grunt 时代,Web 开发要做的事情变多,流程复杂,自动化思想被引入,用于简化流程;

Grunt

Gulp

在 Gulp 时代,开始出现一些新语言用于提高开发效率,流程处理思想的出现是为了简化文件转换的流程,例如将ES6转换为ES5;

语法太简洁了。感觉一句多余的代码都没有。或者说它只让你写必要的代码。用gulp官网的话说,这个叫做“代码优于配置”

构建项目的时间速度快。它充分利用了node流,优化(缩减)了很多对IO的操作。这样做的好处是你会发现gulp构建的时候每个Tast几乎都是ms级的,用了这个以后你会感觉grunt构建时候的速度原来那么慢。

FIS 3

Fis3是一个来自百度的优秀国产构建工具。相对于 Grunt、Gulp 这些只提供了基本功能的工具。Fis3集成了开发者常用的构建功能,如下所述。
读写文件:通过 fis.match 读文件,release 配置文件输出路径。
资源定位:解析文件之间的依赖关系和文件位置。
文件指纹:在通过 useHash 配置输出文件时为文件 URL加上 md5 戳,来优化浏览器的缓存。
文件编译:通过 parser 配置文件解析器做文件转换,例如将 ES6 编译成 ES5。
压缩资源:通过 optimizer 配置代码压缩方法。
图片合并:通过 spriter 配置合并 CSS 里导入的图片到一个文件中,来减少 HTTP 请求数。

Webpack

在Webpack时代,由于单页应用的流行,网页的功能和实现代码变的复杂、庞大,Web开发向模块化改进
(本地模块化工具)
Webpack 是一个打包模块化的JavaScript的工具,在Webpack里一切文件皆模块,通过 loader 转换文件,通过Plugin 注入钩子,最后输出由多个模块组合成的文件。Webpack 专注于构建模块化项目。

Rollup

Rollup 是一个和 Webpack 很类似但专注于ES6的模块打包工具。它的亮点在于,针对ES6源码进行 Tree Shaking,以去除那些已经被定义但没被使用的代码并进行 Scope Hoisting,以减少输出文件的大小和提升运行性能。然而 Rollup 的这些亮点随后就被 Webpack 模仿和实现了。由于 Rollup 的使用方法和 Webpakc 差不多,所以这里就不详细介绍如何使用 Rollup 了,而是详细说明他们的差别:
Rollup 是在Webpack 流行后出现的替代品;
Rollup 生态链不完善,体验还不如Webpack;
Rollup 的功能不如 Webpack 完善,但其配置和使用更简单;
Rollup 不支持 Code Spliting, 但好处是在打包出来的代码中没有 Webpack 那段模块的加载、执行和缓存的代码。
Rollup 在用于打包JavaScript库时比 Webpack 更有优势,因为其打包出来的代码更小、更快。但他的功能不够完善,在很多场景下都找不到现成的解决方案。

Overview

  • 在 Npm Scripts 和 Grunt 时代,Web 开发要做的事情变多,流程复杂,自动化思想被引入,用于简化流程;
  • 在 Gulp 时代,开始出现一些新语言用于提高开发效率,流程处理思想的出现是为了简化文件转换的流程,例如将ES6转换为ES5;
  • 在Webpack时代,由于单页应用的流行,网页的功能和实现代码变的复杂、庞大,Web开发向模块化改进。

Web 前端项目的演进

从简单到复杂
从多页到单页
前后端的分离
前端模块化/组件化/工程化

具体的演进过程如下

多页

后端直接输出 Web 内容, 没有异步请求后端接口数据

多页 + Ajax + 拼字符串输出 HTML

静态页面变成”动态”页面, 需要调用后端接口获取数据, 在前端渲染出页面的内容

多页 + Ajax + 前端模版引擎(artTemplate)

拼字符串难以维护, 引入前端模版引擎来实现数据层与展现层的分离
多页 + Ajax + 前端 MVVM 框架(Vue)
引入前端 MVVM 框架来取代前端模版引擎, 数据与视图同步更新, 更彻底的分离出展现层

多页 + Ajax + 前端 MVVM 框架(Vue) + (模块化)依赖管理(RequireJS)

前端的依赖混乱难以管理一直是前端的毒瘤, 项目变大后团队的协作是个问题, 很容易就发生 JS(全局) 和 CSS(全局) 的冲突
JS 和 CSS 本身在语言层次上没有提供模块化解决方案
JS 一般通过闭包导出命名空间到全局来规避冲突, 实现简易的模块化
CSS 一般通过命名规范来规避冲突, 例如 BEM 命名规范
如果只是简单的项目, 可以引入历史技术 AMD 来实现模块化和依赖管理
一旦有了模块化管理, 势必会慢慢涉及到前端构建方案(Grunt/Gulp), 来做前端的打包和发布

单页 + Ajax + 前端 MVVM 框架(Vue) + (模块化)依赖管理(webpack/ES2015) + 前端路由(vue-router)

单页的复杂度是前端的一个转折点, 你会遇到越来越多前端工程化方面的问题, 首先需要了解的就是前端路由的实现原理(hashchange/HistoryAPI)
因为实现单页的基础就是引入前端路由来模拟出”多个页面视图”的逻辑切换
模块化之后, 为了模块的重用, 一般会定义出公共模块和各个页面视图模块, 模块的数量会越来越多, 首次需要加载的文件也就会越来越多, 你肯定不想浏览器首次加载的时候需要发送几十个请求吧, 因此我们需要前端构建工具来打包我们的模块
然而你肯定也不想所有的模块都打包成一个文件(all in one), 这样肯定会拖慢页面首屏加载的速度, 因此迫切的需要代码分隔和模块懒加载(一般是根据路由的懒加载)
那么既然已经引入了前端工程化构建的过程, 那么前端一些最新的规范(例如 ES2015), 我们也就可以用起来了, 让我们面向未来编程

单页 + Ajax + 前端 MVVM 框架(Vue) + (模块化)依赖管理(webpack/ES2015) + 前端路由(vue-router) + 状态管理(Redux)

页面视图上需要控制的状态越来越多, 多个页面视图的状态又有依赖, 到底是哪里触发了某个状态的改变, 哪个视图又会受到这个状态改变的影响?
你是不是通过全局事件做过组件之间的通信? 你能够预测到状态与视图之间的对应关系吗? 是不是越发地难以控制难以调试了?
引入前端状态管理的架构方案让代码结构标准化可控
view = f(state)

前端模块化/组件化/工程化

将前端项目当成一项系统工程进行分析、组织和构建从而达到项目结构清晰、分工明确、团队配合默契、开发效率提高的目.

模块化和组件化一个最直接的好处就是复用,同时我们也应该有一个理念,模块化和组件化除了复用之外还有就是分治,我们能够在不影响其他代码的情况下按需修改某一独立的模块或是组件,因此很多地方我们及时没有很强烈的复用需要也可以根据分治需求进行模块化或组件化开发。

Apple VPP (Volume Purchase Program)

VPP means “Volume Purchase Program”. The Volume Purchase Program allows businesses and educational institutions to purchase your apps in volume and distribute them within their organizations. Contract developers can also offer customized apps to customers who have a Volume Purchase Program for Business account.

It is said ‘Whether you have ten employees or ten thousand, the Volume Purchase Program makes it simple to find, buy, and distribute apps and books to meet your every business need’. It just a way to help our customer distribute our App. Customers need to register an account from Apple to use it first. Then “Using an MDM solution, assign apps directly to your devices or invite users to participate if distributing via Apple ID.”

Develop Custom Apps for Business

It allow you to engage with business customers to design and build customized apps that work best for them. Custom B2B apps are delivered privately through the Volume Purchase Program. You can distribute to authorized buyers that you identify, giving your business customers privacy and security.

Customize Apps

Meet the unique needs of businesses by privately offering custom B2B apps to Volume Purchase Program for Business members.

  • Tailored look and feel, such as company logo or branding
  • Specific functionality for a business process or workflow
  • Special configuration for IT environments
  • Security features for sensitive or private company data
  • Custom features for partners, dealers, or franchises

Distribute Privately

Custom apps are distributed privately to authorized Volume Purchase Program for Business members that you identify in iTunes Connect. Customers sign in and purchase their apps on the Volume Purchase Program store.

Submit as B2B apps

Setup and develop is the same as normal apple store ones. Only the submit is a little different. Select the custom B2B distribution option in iTunes Connect. If your app contains sensitive data, provide sample data and authentication for our review team.

What Business Customers Need to Do

  • Enroll: Once your customer has a volume purchasing account with Apple, they can easily buy apps that meet their business needs, and get custom B2B apps you’ve built for them.
  • Purchase: Custom B2B apps will appear in your customer’s Volume Purchase Program account. Customers select the app and enter the quantity they want to purchase on the Volume Purchase Program store
  • DistributeYour business customers can use third-party Mobile Device Management (MDM) solutions to help manage and distribute their apps. Or they can provide redemption codes to their users via email or an internal website.

Node.js Interview Questions and Answers


More Readings

Basic Questions

In JavaScript, which types are pass by reference? And which types are pass by value? How to pass a variable by reference?

Simply speaking, objects are pass by reference. Basic types are pass by value. We can pass basic types by reference using boxing technique.

Pass by reference and pass by value is a basic question. It is fundamental part to understand how does JavaScript’s memory work. It is hardly to have further discussion without understanding reference.

In coding session, we use questions like how to write a json object copy function to assess candidate.

Sometimes, we ask about the difference between == and ===. And then, true or false of [1] == [1]. Without a good foundation, candidate may make a wrong conclusion because of the wrong understanding of == and ===.

More on pure javascript: Javascript Interview Questions and Answers

How to judge whether a interface is asynchronous? Is it asynchronous while a callback provided?

This is a open question, you can have your own way to judge.

Simply use the callback function is not asynchronous, IO operation may be asynchronous, in addition to the use of setTimeout and other ways are asynchronous.

How to implement a Sleep function?

1
2
3
4
5
function sleep(sleepMs) {
var start = Date.now(), expire = start + sleepMs;
while (Date.now() < expire) ;
return;
}

Node.js Modules

What is V8 module

We are not talking about V8, but V8 module in Node.js. It’s used for opening built-in events and interfaces of V8 engine in Node.js. Because these interfaces are defined by underlying part of V8, so we can’t say it’s absolutely stable.

Is the Eventemitter.emit synchronous or asynchronous?

Synchronous.

Events module is a very important core module in Node.js. There are many important core APIs in the node that depend on Events , for example, Stream is implemented based on Events, and fs, net, ‘http’ are implemented based on ‘Stream’, ‘Events’ is so important to Node.js.

The EventListener calls all listeners synchronously in the order in which they were registered. This is important to ensure the proper sequencing of events and to avoid race conditions or logic errors.
And when you destroy this class, don’t forget to destroy these emitters too , because inside the class, some listener may cause memory leak.

if a website has a interface A, and in some cases, interface A can be the endless loop, unfortunately, if you triggered this endless loop, what will be the impact on your website?

If endless loop logic trigger in your website, the whole process will be blocked, and all request will timeout, asynchronous code will never be executed, and your website will be crashed.

In Node.js environment javascript code has only one single thread. Only the current code has been executed, the process will cut into the event loop, and then pop out the next callback function from the event queue to start the implementation of the code, as long as an infinite loop can block the execution of the entire js process

How to implement an async.reduce

You need to know that reduce is analyze a recursive data structure and through use of a given combining operation, recombine the results of recursively processing its constituent parts, building up a return value.

What’re the difference between child_process.fork and fork in POSIX?

In Node.js, child_process.fork() calls POSIX fork(2). You need manually manage the release of resources in the child process for fork POSIX. You don’t need to care about this problem when using child_process.fork, beacuse Node.js will automatic release, and provide options whether the child process can survive after the parent process is destroyed.

Does the death of parent process or child process affect each other? What is an orphan process?

The death of a child process will not affect the parent process. When the child process dies (the last thread of the thread group, usually when the “lead” thread dies), it will send a death signal to its parent process. On the other hand, when the parent process dies, by default, the child process will follow the death. But at this time, if the child process is in the operational state, dead state, etc., it will be adopted by process identifier 1(the init system process) and become an orphaned process. In addition, when the child process dies(“terminated” state), the parent process does not call wait() or waitpid() to return the child’s information in time, there is a PCB remaining in the process table. The child process is called a zombie process.

IPC(Inter-process communication), Before IPC channel was set up, how the parent process and the child process communicate between each other? If there is no communication, how is IPC set up?

When you create a child process via child_process, you can specify the env (environment variable) of the child process. When starting the child process in Node.js, the main process sets up the IPC channel first, then pass the fd(file descriptor) of the IPC channel to the child process via environment variable (NODE_CHANNEL_FD). Then the child process connects to the parent process via fd.

Finally, for the issue of inter-process communication (IPC), we generally do not directly ask the IPC implementation, but will ask under what conditions you need IPC, and the use of IPC to deal with any business scene.

What is Daemon Process

Daemon Process is a very basic concept of the server side. Many people may only know that we can start a process as a daemon by using tools such as pm2, but not what is a process and why using it. For excellent guys, daemon process implement should be known.

The normal process will be directly shut down after the user exits the terminal. The Process starting with & and running in the background will be shut down when the session (session group) is released. The daemon process is not dependent on the terminal(tty) process and will not be shut down because of the user exiting the terminal.

What is Buffer

Buffer is the class to handle binary data in Node.js, IO-related operations (network / file, etc.) are all based on Buffer. An instance of the Buffer class is very similar to an array of integers, but its size is fixed, And its original memory space is allocated outside the V8 stack. After the instance of the Buffer class is created, the memory size occupied by it can no longer be adjusted.

New Buffer () interface was deprecated from Node.js v6.x, The reason is that different types of parameters will return different types of Buffer objects, So when the developer does not correctly verify the parameters or does not correctly initialize the contents of the Buffer object, it will inadvertently introduce security and reliability problems to the code.

What is String Decoder

String Decoder is a module to decode buffers to strings, as a supplement to Buffer.toString, it supports multi-byte UTF-8 and UTF-16 characters. Such as:

1
2
3
4
5
6
7
8
const StringDecoder = require('string_decoder').StringDecoder;
const decoder = new StringDecoder('utf8');

const cent = Buffer.from([0xC2, 0xA2]);
console.log(decoder.write(cent)); // ¢

const euro = Buffer.from([0xE2, 0x82, 0xAC]);
console.log(decoder.write(euro)); // €

What’s the current working directory of the process? What’s it for?

You can obtain the current working directory by using process.cwd(). It usually is the directory when the command line starts. It can also be specified at startup. File operations, etc. obtain the file by using the relative path which is relative to the current working directory.

Some of the third-party modules that can obtain the configuration look for the configuration file through your current directory. So if running the start script in the wrong directory, you will get wrong rusults. You can change working directory by using process.chdir() in your code.

How should I handle unexpected errors? Should I use try/catch, domains, or something else?

Here are the error handling methods in Node.js:

  • callback(err, data) Callback agreement
  • throw / try / catch
  • Error event of EventEmitter

What is uncaughtException

he uncaughtException event of process object will be triggered when the exception is not caught and bubbling to the Event Loop. By default, Node.js will ouput the stack trace information to the stderr and end process for such exceptions, And adding listener to uncaughtException event can override the default behavior, thus not end the process directly.

1
2
3
process.on('uncaughtException', (err) => {
console.log(`Caught exception: ${err}`);
});

Should we use Domain for error handling?

No.
In the early Node.js, try/catch is unable to capture asynchronous errors, And the error first callback is just an agreement, without mandatory and very cumbersome to write. So in order to catch the exception very well, Node.js introduces domain module in v0.8.

But domain also brought more new problems. Such as dependent modules can not inherit the domain you defined, Causing it can’t cover errors in dependent modules. Furthermore, Many people (especially new bie) didn’t understand memory / asynchronous processes and other issues in Node.js, they didn’t do well when using domain to process errors and let the code continue, this is likely to cause the project to be completely unserviceable (Any problems are possible, And all kinds of shit…)

And now, it is ‘deprecate’.

Top 5 Frameworks for Mobile Hybrid Apps in 2018

If you’re the one who still doesn’t know this term, an hybrid mobile application is a combination of HTML5/JavaScript/CSS code and some kind of native application wrapper (Cordova and PhoneGap). Typically, a wrapper framework, like PhoneGap, provides the native code which bridges a gap between the native side and a JavaScript API. This way, an application JavaScript code can perform native functions, for example taking a picture with the camera.

Apache Cordova (Phonegap)

Phonegap- One of the most popular cross—platform framework is Phonegap. The team behind Apache Cordova, the Adobe PhoneGap framework is an open source distribution of Cordova framework. The biggest advantage of using this framework is that a hybrid app developer can reuse existing web development skills and create an application by using HTML, CSS, and JavaScript for multiple platforms with a single codebase.

If you go through the core of Apache Cordova applications, you will find them using CSS3 and HTML5 in order to get easy access to underlying hardware such as the accelerometer, camera, and GPS. In fact, it can be extended with native plugins from JavaScript to add more functionalities, so that it can communicate directly between the native layer and HTML5 Page. Also, the plugins allow access to the device’s accelerometer, camera, compass, file system, microphone, and more.

Ionic (Built on Cordova)

Ionic- Ionic is a complete open-source SDK, powered by a massive world-wide community. Built on top of Angular.js and Apache Cordova, the framework provides tools and services for developing hybrid mobile apps. Almost all the apps are built with the help of web technologies like CSS, HTML5, and Sass and then easily distributed through native app stores. It may quite interest you to know that the community incorporates over 120 native device features like Bluetooth, HealthKit, Finger Print Auth, and more with Cordova/PhoneGap plugins and TypeScript extensions. No wonder, it’s been the most preferred framework for most of the developers. The simple collaboration with AngularJS turned out to be sufficient to harness the full potential of the framework.

Last but certainly not the least, Ionic offers a command line interface representing some awesome features, which can be further be integrated and more useful features like deep linking, AoT Compiling, Ionic Native.

Framework 7

Framework 7 is incredibly popular. It’s been around for a fairly long time, and has been used in production by a number of smaller companies.

Originally developed with only iOS in mind, Framework 7 has since expanded to Material Design as well. The themes for both platforms are excellently designed, meshing fairly well with native controls. The animations and gestures do feel a bit odd though, and I’m not sure why. As an added bonus, Framework 7 is designed to be extensible via. plugins, though the majority of them seem to be designed for plain vanilla usage, not for Vue.

It contains an absolutely massive selection of components, and quite a bit of documentation to go with them. However, it does not appear to support custom themes, at least not out-of-the-box. You may have to do it yourself with CSS overrides.

Framework 7 is a proven framework that provides just about everything you need for a hybrid web app.

However, Framework 7 prefers to use its own built-in libraries over allowing you to choose, instead opting to use its own routing and DOM management systems, and offers little in the way of themeing choices. If that’s fine with you, than go with it.

Xamarin

Xamarin is a Microsoft-owned San Francisco, a California-based software company founded in May 2011 which has cross-platform implementations of the Common Language Infrastructure (CLI) and Common Language Specifications (often called Microsoft .NET).

With a C# shared codebase, developers can use Xamarin tools to write native Android, iOS, and Windows apps with native user interfaces and share code across multiple platforms, including Windows and MacOS. Xamarin is the top hybrid mobile app development framework. It saves your time regarding re-utilizing abilities, tools, teams and the best significant part is code. You can influence the array of Xamarin and Android APIs as well as design an amazing experience for glass with the Android SDK and GDK.

React/React Native

  • React.js is an open source Single Page Application (SPA) framework that allows web developers the ability to build large scale JavaScript applications for the browser. It composes common application requirements (such as rendering views) into a single framework that can be leveraged for productivity.
  • React Native is an extension of react that removes browser specific features and introduces mobile specific knowledge. Facebook are key contributers to this project.

The framework isn’t tailored towards novice in the field of web development but certainly, presents a brighter side. React Native framework offers a couple of advantages such as native-like performance and vast community.

Conclusion

If you’re planning to create a mobile application, choosing the hybrid model will save you time and effort and you can reuse the code for creating a web application version too. Of course, the hybrid model is not the perfect solution for all problems, but hybrid apps are a good choice for deploying your app faster and for creating prototype applications, for example. These frameworks can surely provide you a user experience very close to a native application.

ES6 Interview Questions and Answers

image

What is javascript ES6

  • ES6 – also known as Harmony, es-next, ES2015 – is the latest finalized specification of the language
  • The ES6 specification was finalized in June 2015, (hence ES2015)
  • Future versions of the specification will follow the ES[YYYY] pattern, e.g ES2016 for ES7

What is Arrow Functions

Arrows are a function shorthand using the => syntax. They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript. They support both statement block bodies as well as expression bodies which return the value of the expression. Unlike functions, arrows share the same lexical this as their surrounding code.

  • Terse way to declare a function like param => returnValue
  • Useful when doing functional stuff like [1, 2, 3].map(x => x * 2)
  • You can’t name arrow functions statically, but runtimes are now much better at inferring names for most methods
    1
    2
    // e.g.
    var odds = evens.map(v => v + 1);

    how to use Classes in ES6

    ES6 classes are a simple sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.

What is Template Strings(Template Literals)

Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.

  • You can declare strings with ` (backticks), in addition to " and '
  • Strings wrapped in backticks are template literals
  • Template literals can be multiline
  • Template literals allow interpolation like `ponyfoo.com is ${rating}` where rating is a variable
  • You can use any valid JavaScript expressions in the interpolation, such as `${2 * 3}` or `${foo()}`
  • You can use tagged templates to change how expressions are interpolated
    • Add a fn prefix to fn`foo, ${bar} and ${baz}`
    • fn is called once with template, ...expressions
    • template is ['foo, ', ' and ', ''] and expressions is [bar, baz]
    • The result of fn becomes the value of the template literal
    • Possible use cases include input sanitization of expressions, parameter parsing, etc.
  • Template literals are almost strictly better than strings wrapped in single or double quotes
    e.g
    1
    2
    var name = "node.js", time = "today";
    `hi${name}, how are you ${time}?`

How to use Multi-line Strings in ES6

In ES5, we had to use one of these approaches:

1
2
var hello = 'Welcome to \n'
+ 'http://top10webjs.com';

While in ES6, simply utilize the backticks:

1
2
var hello = `Welcome to 
http://top10webjs.com`;

What is Destructuring Assignment in ES6

Destructuring in the ES6 refers to the use of patterns to effectively match values to variables or properties. It’s hard to describe in words, so an example using the more common array pattern should help:

1
2
3
4
5
6
7
8
// e.g. in ES5
var data = $('body').data(), // data has properties house and mouse
house = data.house,
mouse = data.mouse;

// In ES6, we can replace the ES5 code above with these statements:
// we'll get house and mouse variables
var { house, mouse} = $('body').data();

This also works with arrays. e.g.

1
2
var [col1, col2]  = $('.column'),
[line1, line2, line3, , line5] = file.split('\n')

Let v.s. Const

  • let and const are alternatives to var when declaring variables
  • let is block-scoped instead of lexically scoped to a function
  • let is hoisted to the top of the block, while var declarations are hoisted to top of the function
  • const is also block-scoped, hoisted, and constrained by TDZ semantics
  • const variables must be declared using an initializer, const foo = 'bar'
  • Assigning to const after initialization fails silently (or loudly – with an exception – under strict mode)
  • const variables don’t make the assigned value immutable
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    function f() {
    {
    let x;
    {
    // okay, block scoped name
    const x = "sneaky";
    // error, const
    x = "foo";
    }
    // error, already declared in block
    let x = "inner";
    }
    }

How to use Default Parameters

In ES6, we can simply supply default values for parameters in a function, like this:

1
2
3
function add(x=0, y=0) {
return x + y;
}

Iterators + For..Of

Iterator objects enable custom iteration like CLR IEnumerable or Java Iterable. Generalize for..in to custom iterator-based iteration with for..of. Don’t require realizing an array, enabling lazy design patterns like LINQ.

Map, Set, WeakMap, WeakSet

Efficient data structures for common algorithms. WeakMaps provides leak-free object-key’d side tables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Sets
var s = new Set();
s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") === true;

// Maps
var m = new Map();
m.set("hello", 42);
m.set(s, 34);
m.get(s) == 34;

// Weak Maps
var wm = new WeakMap();
wm.set(s, { extra: 42 });
wm.size === undefined

// Weak Sets
var ws = new WeakSet();
ws.add({ data: 42 });
// Because the added object has no other references, it will not be held in the set

what is Promises

Promises are a library for asynchronous programming. Promises are a first class representation of a value that may be made available in the future. Promises are used in many existing JavaScript libraries.
e.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
function timeout(duration = 0) {
return new Promise((resolve, reject) => {
setTimeout(resolve, duration);
})
}

var p = timeout(1000).then(() => {
return timeout(2000);
}).then(() => {
throw new Error("hmm");
}).catch(err => {
return Promise.all([timeout(100), timeout(200)]);
})

New string functions in ES6

In ES6, the standard library has grown immensely. Along with these changes are new methods which can be used on strings, such as .includes() and .repeat(). e.g.

1
2
console.log("abcd".includes("abc"));	  // true
console.log("abc".repeat(3); // 'abcabcabc'

What is Proxy

Proxies enable creation of objects with the full range of behaviors available to host objects. Can be used for interception, object virtualization, logging/profiling, etc. e.g.

1
2
3
4
5
6
7
8
9
var foo= function () { return 'in foo()'; };
var handler = {
apply: function (receiver, ...args) {
return 'in proxy';
}
};

var p = new Proxy(foo, handler);
p() === 'in proxy';

What is Modules & Module Loaders

Language-level support for modules for component definition. Codifies patterns from popular JavaScript module loaders (AMD, CommonJS). Runtime behaviour defined by a host-defined default loader. Implicitly async model – no code executes until requested modules are available and processed.

Module loaders support:

  • Dynamic loading
  • State isolation
  • Global namespace isolation
  • Compilation hooks
  • Nested virtualization
    The default module loader can be configured, and new loaders can be constructed to evaluate and load code in isolated or constrained contexts.

Useful MS-DOS commands

Tasklist

Tasklist displays a list of currently running processes on either a local or remote machine.

e.g. list all chrome processes

tasklist /FI “imagename eq chrome.exe”

e.g. takes the output displayed by tasklist and saves it to the process.txt file.

tasklist > process.txt

e.g. displays any currently running tasks that are using more than 50 MB of memory.
tasklist /fi “memusage gt 50000”

Tree

List file and folders in tree view.

iOS browser cannot get keyboard key for keypress/keydown

1
2
3
4
5
ele.addEventListener('keypress', function(event) {
if (event.key === "Backspace") {
// Do something here
}
});

For this javascript, if you test on PC, or android, it works fine. But if you run on iOS, including webview of iOS. You will find that the webview cannot get the key of the keyboard, e.g. “Backspace”. Quite strange.

But there is a workaround for it - Use “keyCode” instead of “key”; And the above code can write in this way:

1
2
3
4
5
ele.addEventListener('keypress', function(event) {
if (event.key === "Backspace" || event.event.key === 8) {
// Do something here
}
});

OK, it works as expected!

CloudWatch, Azure Monitor, and Stackdriver

Overview

  • Amazon CloudWatch is the platform that monitors Amazon Web Services (AWS).
  • Azure Monitor is Microsoft’s built-in monitoring service for the performance and health of Azure resources. At its most basic level, the model is similar to Cloudwatch: Azure Monitor consumes the telemetry data (performance and log data) that all Azure services generate and allows the user to visualize, query, route, archive, and take actions on the data.
  • Stackdriver, Google’s offering for delivering cloud monitoring capabilities, differs from both Cloudwatch and Azure monitor in a number of ways. Firstly, Stackdriver embraces not only Google Cloud Platform (GCP) but also AWS, providing unified monitoring of the two cloud platforms. Google touts Stackdriver’s multi-cloud strategy and, given Amazon’s prominent standing, it certainly broadens Stackdriver’s appeal.

Stackdriver

Stackdriver also includes a development (DevOPs) component in addition to IT monitoring. However, while the IT Operations functionality spans both AWS and GCP, the DevOPs functionality is Google-centric. Stackdriver is able to troubleshoot deployments on the Google platform with tracing and debugging functionality, and offers capabilities such as:

  • Stackdriver Monitoring measures the health of cloud resources and applications by providing visibility into metrics such as CPU usage, disk I/O, memory, network traffic and uptime. It is based on collectd, an open source daemon that collects system and application performance metrics. Users can receive customizable alerts when Stackdriver Monitoring discovers performance issues. It is used to monitor Google Compute Engine and Amazon EC2 VMs.
  • Stackdriver Error Reporting identifies and analyzes cloud application errors. A centralized error management interface provides IT teams with real-time visibility into production errors with cloud applications, as well as the ability to sort and filter content based on the number of error occurrences, when the error was first and last seen, and where the error is located.
  • Stackdriver Debugger inspects the state of an application, deployed in Google App Engine or Google Compute Engine, using production data and source code. During production, snapshots can be taken of an application’s state and linked back to a specific line location in the source code, without having to add logging statements. This inspection can occur without affecting the performance of the production application.
  • Stackdriver Trace collects network latency data from applications deployed in Google App Engine. Trace data is gathered, analyzed and used to create performance reports to identify network bottlenecks. Trace API and Trace SDK can be used to trace, analyze and optimize custom workloads, as well.
  • Stackdriver Logging provides real-time log management and analysis for cloud applications. Log data can be kept for longer periods of time by archiving it with Google Cloud Storage. The service works with both Google and AWS, and can gather logs from Google Compute Engine, Google App Engine and Amazon EC2.

Stackdriver Monitor

Stackdriver Monitoring collects metrics, events, and metadata from Google Cloud Platform, Amazon Web Services (AWS), hosted uptime probes, application instrumentation, and a variety of common application components including Cassandra, Nginx, Apache Web Server, Elasticsearch and many others. Stackdriver ingests that data and generates insights via dashboards, charts, and alerts.

Monitoring Agent

The Monitoring agent is a collectd-based daemon that gathers system and application metrics from virtual machine instances and sends them to Stackdriver Monitoring. By default, the Monitoring agent collects disk, CPU, network, and process metrics. You can configure the Monitoring agent to monitor third-party applications to get the full list of agent metrics.

Using the Monitoring agent is optional but recommended. Stackdriver Monitoring can access some metrics without the Monitoring agent, including CPU utilization, some disk traffic metrics, network traffic, and uptime information. Stackdriver Monitoring uses the Monitoring agent to access additional system resources and application services in virtual machine (VM) instances. If you want these additional capabilities, you should install the Monitoring agent.

Uptime Checks

Stackdriver can verify the availability of your service by accessing it from locations around the world. You can use the results from these uptime checks in your alerting policies, or you can directly monitor the results in the Stackdriver Monitoring uptime-check dashboards.

Alerting

Alerting gives timely awareness to problems in your cloud applications so you can resolve the problems quickly.

You use the Stackdriver Monitoring Console to set up alerting policies. Each policy specifies the following:

  • Conditions that identify an unhealthy state for a resource or a group of resources.
  • Optional notifications sent through email, SMS, or other channels to let your support team know a resource is unhealthy.
  • Optional documentation that can be included in some types of notifications to help your support team resolve the issue.

When events trigger conditions in one of your alerting policies, Stackdriver Monitoring creates and displays an incident in the Stackdriver Monitoring Console. If you set up notifications, Stackdriver Monitoring also sends notifications to people or third-party notification services. Responders can acknowledge receipt of the notification, but the incident remains open until resources are no longer in an unhealthy state.

Assignment Destructuring in ES6

  • var {foo} = pony is equivalent to var foo = pony.foo
  • var {foo: baz} = pony is equivalent to var baz = pony.foo
  • You can provide default values, var {foo='bar'} = baz yields foo: 'bar' if baz.foo is undefined
  • You can pull as many properties as you like, aliased or not
    • var {foo, bar: baz} = {foo: 0, bar: 1} gets you foo: 0 and baz: 1
  • You can go deeper. var {foo: {bar}} = { foo: { bar: 'baz' } } gets you bar: 'baz'
  • You can alias that too. var {foo: {bar: deep}} = { foo: { bar: 'baz' } } gets you deep: 'baz'
  • Properties that aren’t found yield undefined as usual, e.g: var {foo} = {}
  • Deeply nested properties that aren’t found yield an error, e.g: var {foo: {bar}} = {}
  • It also works for arrays, var [a, b] = [0, 1] yields a: 0 and b: 1
  • You can skip items in an array, var [a, , b] = [0, 1, 2], getting a: 0 and b: 2
  • You can swap without an “aux” variable, [a, b] = [b, a]
  • You can also use destructuring in function parameters
    • Assign default values like function foo (bar=2) {}
    • Those defaults can be objects, too function foo (bar={ a: 1, b: 2 }) {}
    • Destructure bar completely, like function foo ({ a=1, b=2 }) {}
    • Default to an empty object if nothing is provided, like function foo ({ a=1, b=2 } = {}) {}