How to read and write file using fs in node

Issue #419 function write(json) { const data = JSON.stringify(json) const year = const directory = `collected/${slugify(className)}/${year}` fs.mkdirSync(directory, { recursive: true }) fs.writeFileSync( `${directory}/${slugify(studentName)}`, data, { overwrite: true } ) } async function readAll() { const classes = fs.readdirSync('classes') classes.forEach((class) => { const years = fs.readdirSync(`classes/${class}`) years.forEach((year) => { const students = fs.readdirSync(`classes/${class}/${year}`) students.forEach((student) => { const data = fs.readFileSync(`classes/${class}/${year}/${student}) const json = JSON.parse(data) }) }) }) }

September 16, 2019 路 1 min 路 Khoa Pham

How to get videos from vimeo in node

Issue #418 Code Path for user users/nsspain/videos Path for showcase Path for Channels, Groups and Portfolios const Vimeo = require('vimeo').Vimeo const vimeoClient = new Vimeo(vimeoClientId, vimeoClientSecret, vimeoAccessToken) async getVideos(path) { const options = { path: `channels/staffpicks/videos`, query: { page: 1, per_page: 100, fields: 'uri,name,description,created_time,pictures' } } return new Promise((resolve, reject) => { try { vimeoClient.request(options, (error, body, status_code, headers) => { if (isValid(body)) { resolve(body) } else { throw error } }) } catch (e) { reject(e) console....

September 16, 2019 路 2 min 路 Khoa Pham

How to get videos from youtube in node

Issue #417 class Youtube { async getVideos(playlistId, pageToken) { const options = { key: clientKey, part: 'id,contentDetails,snippet', playlistId: playlistId, maxResult: 100, pageToken } return new Promise((resolve, reject) => { try { youtube.playlistItems.list(options, (error, result) => { if (isValid(result)) { resolve(result) } else { throw error } }) } catch (e) { reject(e) } }) } } Response look like { "kind": "youtube#playlistItemListResponse", "etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/ZNTrH71d3sV6gR6BWPeamXI1HhE\"", "nextPageToken": "CAUQAA", "pageInfo": { "totalResults": 32, "resultsPerPage": 5 }, "items": [ { "kind": "youtube#playlistItem", "etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/pt-bElhU3f7Q6c1Wc0URk9GJN-w\"", "id": "UExDbDVOTTRxRDN1X0w4ZEpyV1liTEI4RmNVYW9BSERGdC4yODlGNEE0NkRGMEEzMEQy", "snippet": { "publishedAt": "2019-04-11T06:09:26....

September 13, 2019 路 1 min 路 Khoa Pham

How to convert callback to Promise in Javascript

Issue #416 // @flow const toPromise = (f: (any) => void) => { return new Promise<any>((resolve, reject) => { try { f((result) => { resolve(result) }) } catch (e) { reject(e) } }) } const videos = await toPromise(callback) If a function accepts many parameters, we need to curry function curry2(f) { return (p1) => { return (p2) => { return f(p1, p2) } } } const callback = curry2(aFunctionThatAcceptsOptionsAndCallback)(options) const items = await toPromise(callback)

September 13, 2019 路 1 min 路 Khoa Pham

How to fix electron issues

Issue #415 Electron require() is not defined function createWindow () { win = new BrowserWindow({ title: 'MyApp', width: 600, height: 500, resizable: false, icon: __dirname + '/Icon/Icon.icns', webPreferences: { nodeIntegration: true } }) } DevTools was disconnected from the page npm install babel-cli@latest --save-dev npm install react@16.2.0 win.openDevTools() This leads to Cannot find module 'react/lib/ReactComponentTreeHook' If we鈥檙e using binary, then rebuild, it is the problem that cause devTools not work...

September 12, 2019 路 1 min 路 Khoa Pham

How to make simple traffic simulation in Javascript

Issue #400 Use prototype.js for inheritance Use enchant.js for 2d game logic Code

September 5, 2019 路 1 min 路 Khoa Pham

How to make collaborative drawing canvas with socketio and node

Issue #399 Client Use App.js import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Main from './Main' class App extends Component { render() { return <Main /> } } export default App; Main.js // @flow import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import Button from '@material-ui/core/Button'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import Manager from '....

September 5, 2019 路 2 min 路 Khoa Pham

How to generate changelog for GitHub releases with rxjs and node

Issue #398 How to Use Generate personal access token Technical Dependencies const Rx = require('rxjs/Rx') const Fetch = require('node-fetch') const Minimist = require('minimist') const Fs = require('fs') Use GraphQL makeOptions(query, token) { return { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `bearer ${token}` }, body: JSON.stringify({ query: ` query { repository(owner: "${this.owner}", name: "${this.repo}") { ${query}} } ` }) } } Use orderBy fetchPRsAndIssues(dates) { const query = ` pullRequests(last: 100, orderBy: {field: UPDATED_AT, direction: ASC}) { edges { node { title merged mergedAt url author { login url } } } } issues(last: 100, orderBy: {field: UPDATED_AT, direction: ASC}) { edges { node { title closed updatedAt url } } } } }

September 5, 2019 路 1 min 路 Khoa Pham

How to get all GitHub issues using GraphQL

Issue #393 query { repository(owner: "onmyway133", name: "blog") { issues(orderBy: {field: UPDATED_AT, direction: ASC}, last: 100) { edges { cursor node { title createdAt updatedAt labels(first: 10) { edges { node { name } } } } } } } } In node.js const GraphQL = require('graphql-request') const GraphQLClient = GraphQL.GraphQLClient const client = new GraphQLClient('', { headers: { Authorization: 'Bearer 123456730712334152e6e1232c53987654312', }, }) const query = `{ repository(owner: "onmyway133", name: "blog") { issues(first: 100) { edges { node { title createdAt updatedAt labels(first: 10) { edges { node { name } } } } } } } }` client....

September 3, 2019 路 1 min 路 Khoa Pham

How to use Hexo to deploy static site

Issue #392 It鈥檚 been a long journey since, next step is to keep GitHub issues as source, and mirror those to a static site. Use 2 repos for source for generated content npm install -g hexo-cli echo $PATH=$PATH:/Users/khoa/.nodenv/versions/10.15.2/bin/hexo hexo init blog npm install hexo-deployer-git --save Update _config.yml deploy: type: git repo: branch: master hexo clean hexo deploy Read more

September 3, 2019 路 1 min 路 Khoa Pham

How to use type coersion in Javascript

Issue #391 People who make fun of Javascript probably don鈥檛 understand implicit type coersion and when to use triple equal. Javascript is very unexpected, but when we work with this language, we need to be aware. Coercion鈥揂utomatically changing a value from one type to another. If x is Number and y is String, return x == ToNumber(y) If x is String or Number and y is Object, return x == ToPrimitive(y) Empty array becomes empty string Read more https://codeburst....

September 3, 2019 路 1 min 路 Khoa Pham

How to safely access deeply nested object in Javascript

Issue #390 An object 鈥檚 property can be null or undefined. Accessing step by step is tedious props.user && props.user.posts && props.user.posts[0] && props.user.posts[0].comments Dynamic parsing path is too clever and involves string in the end, which is a no no const get = (p, o) => p.reduce((xs, x) => (xs && xs[x]) ? xs[x] : null, o) const getUserComments = get(['user', 'posts', 0, 'comments']) Instead let鈥檚 use function and catch errors explicitly, and defaults with a fallback...

September 3, 2019 路 1 min 路 Khoa Pham

How to use flow type in Javascript

Issue #389 Prefer flow over TypeScript for simplicity Javascript primitive types number and string are too general and do not express the domain objects. Because lack of type alias in Javascript, we can use flow export type Centimeter = number export type Color = string export type ImageSource = number export type Kilogram = number export type Kilocalorie = number // 1 cal = 4.1840 J export type Second = number export type SecondsSince1970 = number export type Minute = number export type DateString = string // 2018-11-20 export type DateTimeString = string // 2018-11-20T00:00:00 export type YearWeekString = string // 201838 export type FunctionWithVoid = () => void export type FunctionWithString = (string) => void export type FunctionWithBoolean = (boolean) => void export type FunctionWithNumber = (number) => void export type JSONObject = any export type JSONString = string export type StringToString = any export type Degree = number export type Radian = number export type Animal = 'cat' | 'dog' | 'cow'

September 3, 2019 路 1 min 路 Khoa Pham

How to use React JSX with Babel in Electron

Issue #352 For a normal electron app created with npm init, we can use all features of ES6, but not the JSX syntax for React. We can use just Babel to transpile JSX, as used in IconGenerator .babelrc { "plugins": [ "transform-react-jsx-source" ], "presets": ["env", "react"] } And in package.json, call babel to transpile src to dist "main": "dist/main.js", "scripts": { "start": "npm run babel && electron .", "babel": "babel ....

August 12, 2019 路 1 min 路 Khoa Pham

How to submit electron app to AppStore

Issue #342 Before Install electron as dev npm install electron --save-dev Update electron-packager npm install electron-packager@latest --save-dev Use no space in app name Package with electron-packager Follow npx electron-packager . "MyApp" --app-bundle-id=com.onmyway133.MyApp --helper-bundle-id=com.onmyway133.MyApp.helper --app-version=1.4.0 --build-version=1.0.100 --platform=mas --arch=x64 --icon=Icon/Icon.icns --overwrite npx electron-osx-sign "MyApp-mas-x64/" --verbose npx electron-osx-flat "MyApp-mas-x64/" --verbose If you have multiple developer identities in your keychain: electron-osx-sign searches your keychain for the first signing certificates that it can locate....

July 31, 2019 路 2 min 路 Khoa Pham

How to organise test files

Issue #327 In terms of tests, we usually have files for unit test, UI test, integeration test and mock. Out of sight, out of mind. Unit tests are for checking specific functions and classes, it鈥檚 more convenient to browse them side by side with source file. For example in Javascript, Kotlin and Swift index.js index.test.js index.mock.js LocationManager.kt LocationManager.mock.kt LocationManager.test.kt BasketHandler.swift BasketHandler.mock.swift BasketHandler.test.swift Integration tests check features or sub features, and may cover many source files, it鈥檚 better to place them in feature folders...

June 25, 2019 路 1 min 路 Khoa Pham

What is create-react-native-app

Issue #279 Original post As someone who comes to React Native from iOS and Android background, I like React and Javascript as much as I like Swift and Kotlin. React Native is a cool concept, but things that sound good in theory may not work well in practice. Another layer of abstraction Up until now, I still don鈥檛 get why big companies choose React Native over native ones, as in the end what we do is to deliver good experience to the end user, not the easy development for developers....

May 23, 2019 路 5 min 路 Khoa Pham

How to make tag selection view in React Native

Issue #271 Original post Besides React style programming, Yoga is another cool feature of React Native. It is a cross-platform layout engine which implements Flexbox so we use the same layout code for both platforms. As someone who uses Auto Layout in iOS and Constraint Layout in Android, I find Flexbox bit hard to use at first, but there are many tasks that Flexbox does very well, they are distribute elements in space and flow layout....

May 23, 2019 路 6 min 路 Khoa Pham

Getting to know some pragmatic programming language features

Issue #270 As you know, in the Pragmatic Programmer, section Your Knowledge Portfolio, it is said that Learn at least one new language every year. Different languages solve the same problems in different ways. By learning several different approaches, you can help broaden your thinking and avoid getting stuck in a rut. Additionally, learning many languages is far easier now, thanks to the wealth of freely available software on the Internet...

May 23, 2019 路 8 min 路 Khoa Pham

How to add app icons and splash screens to a React Native app in staging and production

Issue #268 React Native was designed to be 鈥渓earn once, write anywhere,鈥 and it is usually used to build cross platform apps for iOS and Android. And for each app that we build, there are times we need to reuse the same code, build and tweak it a bit to make it work for different environments. For example, we might need multiple skins, themes, a free and paid version, or more often different staging and production environments....

May 23, 2019 路 12 min 路 Khoa Pham