Skip to content. | Skip to navigation

Personal tools

Navigation

You are here: Home / Tutorial / Node.js

Node.js

Node.js 以 V8 JavaScript runtime 為基礎,使用 C++ 寫成,透過 NPM 來管理模組,並在 Grunt, Gulp, Webpack 工具的協助下,發展成廣大生態系。另一個模組管理程式 Yarn 改善了效能與安全,模組的相依關係與版本由 lockfiles 來管理。 https://medium.com/@priyeshsaraswat9/asynchronous-adventures-with-node-js-5c7463970efd https://medium.com/@shreyvijayvargiya26/perfect-express-architecture-ba28c2bfc8b3 https://polinwei.com/npm-vs-yarn/

beginners guide to gulp Node.js modules basics to advanced Node.js best practices using modern-features 以資料庫查詢操作為例,傳統實現方式像: res = db.query('SELECT * FROM some_table'); res.output(); 執行到第一行時可能會阻塞,改用 db.query('SELECT * FROM some_table', function(res) { res.output(); }); 裡面的函式被稱為回呼函式,用以改善阻塞的問題。架構上就是以 Event Loop 為處理核心,不致產生多行執緒而防止惡意攻擊。

How might Serverless impact Node.js Ecosystem React.js vs Angular the-typescript-tax File Upload with Node.js understanding JSON in javascript angular unit testing jasmine karma step by step introducing akita a new State Management pattern for Angular Applications

教學 By Example #1 #2 #3 #4 Productivity Tools, Plugins and Libraries Install CLI with the --unsafe-perm Option

Python Essentials for Node.js Developers

19-ways to become better node.js developer in-2019

Ubuntu Tip:

$ curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
$ sudo apt-get install -y nodejs
$ sudo npm install npm --global

## To install the Yarn package manager, run:
     curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
     echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
     sudo apt-get update && sudo apt-get install yarn

Mac Installer: installed at /usr/local/bin/node /usr/local/bin/npm

// app.js
var http = require('http');
http.createServer(function(req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<h1>Node.js</h1>');
  res.end('<p>Hello World</p>');
}).listen(3000);
console.log("HTTP server is listening at port 3000.");

可再安裝 supervisor 來執行上述程式

// readfile.js
var fs = require('fs');
fs.readFile('file.txt', 'utf-8', function(err, data) {
  if (err) {
    console.error(err);
  } else {
    console.log(data);
  }
});
console.log('end.');
// readfilesync.js
var fs = require('fs');
var data = fs.readFileSync('file.txt', 'utf-8');
console.log(data);
console.log('end.');

並不是所有 Node.js API 都提供同步和非同步版本,原則上並不鼓勵同步 IO。

Event 是由 EventEmitter 提供

// event.js
var EventEmitter = require('events').EventEmitter;
var event = new EventEmitter();
event.on('some_event', function() {
  console.log('some_event occured.');
});
setTimeout(function() {
  event.emit('some_event');
}, 1000);

NPM Node Package Manager

Beginner Guide: 分成 local 或 global 模式,前者把檔案安裝在 node_modules 目錄,後者在 {prefix}/lib/node_modules 目錄。另外可參考 global without sudo

設定安裝目錄

$ npm config get prefix
/usr/local
$ npm config set prefix=$HOME/.node_modules_global
$ cat .npmrc

By Example #1

package-lock.json 應該被放進版本管理系統,可協助團隊能建置一致的開發環境。

Functional Programming 的函式庫很多,像 Ramda, lodash, Underscore 都是,但導入過程常有門檻

指定版本的語法 lodash

$ npm install lodash@4.17.4

Tips and Tricks

peerDependencies

npm link discussion

安裝 jQuery 後透過 var $ = require('jquery') 使用

Creating CLI Tool

server vs client example

server.js 負責讀取網址需求並回應

var emptygif = require('emptygif');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);

app.get('/tpx.gif', function(req, res, next) {
  io.emit('visit', {
    ip: req.ip,
    ua: req.headers['user-agent']
  });

  emptygif.sendEmptyGif(req, res, {
    'Content-Type': 'image/gif',
    'Content-Length': emptygif.emptyGifBufferLength,
    'Cache-Control': 'public, max-age=0' // or specify expiry to make sure it will call everytime
  });
});

app.use(express.static(__dirname + '/public'));

server.listen(1337);
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reltime pixel tracking dashboard</title>
<style type="text/css">
.visit {
  margin: 5px 0;
  border-bottom: 1px dotted #CCC;
  padding: 5px 0;
}
.ip {
  margin: 0 10px;
  border-left: 1px dotted #CCC;
  border-right: 1px dotted #CCC;
  padding: 0 5px;
}
</style>
</head>
<body>
<h1>Realtime Pixel Tracking Dashboard</h1>
<div class="visits"></div>

<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.1/moment.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$(function() { var socket = io(); var containerEl = $('.visits'); socket.on('visit', function(visit) { var newItem = '<div class="visit">'; newItem += '<span class="date">' + moment().format('MMMM Do YYYY, HH:mm:ss') + '/span' newItem += '<span class="ip">' + visit.ip + '</span>'; newItem += '<span class="ua">' + visit.ua + '</span></div>'; containerEl.append(newItem); }); }); </script> </body> </html>

Gulp 編譯 SASS 範例

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', function () {
  return gulp.src('./sass/*.sass')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'));
});

Gulp imagemin and boost your sites performance Node.js v6 的 ES6 特色

npm vs yarn npm 5 開始支援 package-lock.json

Passport.js 處理 Authentication 登入 Passport + Express

Debug Tips and Inspector Discord Bot

Browser Storage: IndexedDB

Translator: Babel 7.0.0 Major Breaking Changes

Plone 5 Theme

Preparing the Setup 下列安裝方式應該已不適用

$ sudo apt-get install npm
$ npm install -g grunt-cli 會失敗嗎? 會的話 要修改 theme-package.rst

在專案目錄裡安裝開發環境

$ cd src/my.prj/src/my/prj/theme
$ npm install grunt --save-dev
$ git diff package.json
@@ -4,5 +4,8 @@
   "version": "1.0.0",
   "dependencies": {
     "bootstrap": "^3.3.7"
+  },
+  "devDependencies": {
+    "grunt": "^1.0.3"
   }
 }

自行 local 安裝的方式如下

$ mkdir ~/.npm
$ vi ~/.npmrc  prefix=${HOME}/.npm
$ vi ~/.bashrc NPM_PACKAGEs="${HOME/.npm" PATH="$NPM_PACKAGES/bin:$PATH"
$ source ~/.bashrc
$ npm install grunt-cli
# 可能是較好的步驟
$ cd plone511/zinstance/src/cgis.website
$ npm install
$ npm install grunt-cli --save-dev
$ vi src/cgis/website/theme/barceloneta/less/variables.plone.less
$ node_modules/grunt-cli/bin/grunt compile

Webpack

webpack-dev-server --mode development --open --port 3000

webpack from 0 to automated-testing

summary-of-webpack-4-fundamentals by sean-larkin part-1-of-4 why-webpack

how-to use reactjs with webpack-4-babel-7 and material-design from Grunt to Webpack Webpack2 Beginner Guide setup google analytics React, Webpack, Babel from Scratch Code Splitting with Webpack and React

Resolving Globally Installed Dependencies

Architecture

Deployment

Express 是 Node.js 官方推薦的 Web Framework 除了 http 模組外,還提供路由控制,模板解析,動態視圖,使用者階段,CSRF保護,靜態檔案服務,錯誤控制器,快取,外掛程式支援

var express = require('express');
var app = express.createServer();
app.use(express.bodyParser());
app.all('/', function(req, res) {
  res.send(req.body.title + req.body.text);
});
app.listen(3000);

Express.js Mongo App to AWS https://yami.io/you-might-not-need-nodejs/

security: your silence will not protect you

# to clean up useless modules
npm cache clean --force

Chat App with socket.io Flask + React.js + Socket.io

webkit tutorial: desktop app

Koa 成為取代 Express 的新起之秀

full stack puppy adoption example: knex sqlite orm

shopping app

test case in your Node app using mocha

最近有個專案被掃出 Client Potential XSS 的 issue, 但報告寫的是打包後的 js ``` 方法window["webpackJsonp"]=window["webpackJsonp"]||[]).push在healthindex/js/map.4f1b.js第1 行獲取使用者輸入的value元素。該元素的值於程式流程中沒有被正確地過濾(Filter)或驗證,並最終顯示 於使用者端方法DisplayDetails()在healthindex/js/map.4f1b.js的1行。這可能為跨站腳本(Cross-SiteScripting)攻擊。 ```