nodejs
, backend
https://nodejs.org/en/download/
Ref. https://docs.npmjs.com/try-the-latest-stable-version-of-npm
window
object is provided by the browserglobal
insteaddocument
, fetch
)全域變數 var
: window
上的全域變數會覆寫到 window
,global
則不會(只會在該 js 檔案裡)
In browser: window.prop
In global: global.prop
One of the global object has is process
means the process what is running now in the terminal; what the computer is doing
Exit the process and back to the terminal
globalThis
works outside the browser as wellprocess.exit
to end the processglobal
objects we have.__dirname
to get directory
ES6 imports only works in Node version 12.2.0 or higher
Export: export default var1
Import: import var1 from './filePath'
If ran in older version which Node has not yet been introduced with the ES6 import/export feature: SyntaxError: Unexpected token import
Export: module.exports = { prop1: value1 }
module
is a global object we have access toImport: require('./filePath')
Export: export const variableName = value;
Import: import { variableName } from './filePath'
{}
- destructuring'./script2'
- it's okay not to indicate file typeRun node:
Got an error:
Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
Because Node is created with CommonJS import/export in mind, we needs to specify how we want Node to read the file.
Ref. https://nodejs.org/api/esm.html#enabling
Node.js has two module systems: CommonJS modules and ECMAScript modules. Authors can tell Node.js to use the ECMAScript modules loader via the
.mjs
file extension, the package.json"type"
field, or the--input-type
flag.Outside of those cases, Node.js will use the CommonJS module loader.
.mjs
file method:
.js
to .mjs
files.mjs
import {largeNumber} from './script2.mjs'
$ node script.mjs
package.json
method:
create a package.json
file
-y
to say yes to all the optionsin package.json
file, add "type": "module"
Built-in modules: pre-installed with Node
fs
module - file system modulehttp
module - used to build a serverPackage (e.g. NPM)
nodemon
nodemon
in package.json
's devDependencies
devDependencies
: dependencies we only use when we're developing; won't be included when we actually deployed the appnode_modules/.bin
file, we can use the command $ nodemon
.$npm start
to start nodeman. It will constantly watch the changes and keeps running the $ node script.js
command.__dirname
- 目錄路徑__filename
- 檔名當你載入 var path = require('path');
,便可用下述語法取得檔案與目錄路徑
path.**dirname**('**/xx/yy**/zz.js')
:回傳 /xx/yy
path.**join**(__dirname,'/xx')
回傳 前後路徑合併path.**basename**('/xx/yy/**zz.js**')
- 回傳 zz.js
path.**extname**('/xx/yy/zz.**js**')
- 回傳 js
path.**parse**('/xx/yy/zz.js')
- 回傳 上述綜合物件Ref. Node.js PATH API文件