完整程式碼,請洽: https://github.com/Zrn-code/Node-js-tutorial/tree/node-05
# 安裝包裹 (package)
# 全域包裹 (nodemon)
# npm 初始化
終端機 | PS C:\Users\user\Documents\tuts\node>npm init |
| This utility will walk you through creating a package.json file. |
| It only covers the most common items, and tries to guess sensible defaults. |
| See `npm help init` for definitive documentation on these fields |
| and exactly what they do. |
| Use `npm install <pkg>` afterwards to install a package and |
| save it as a dependency in the package.json file. |
| Press ^C at any time to quit. |
| package name: (node) |
| version: (1.0.0) |
| description: |
| entry point: (server.js) |
| test command: |
| git repository: |
| keywords: |
| author: |
| license: (ISC) |
| About to write to D:\hello\package.json: |
| { |
| "name": "node", |
| "version": "1.0.0", |
| "description": "", |
| "main": "server.js", |
| "scripts": { |
| "test": "echo \"Error: no test specified\" && exit 1", |
| "start": "node server.js" |
| }, |
| "author": "", |
| "license": "ISC" |
| } |
| Is this OK? (yes) |
| package.json |
| { |
| "name": "node", |
| "version": "1.0.0", |
| "description": "", |
| "main": "index.js", |
| "scripts": { |
| "test": "echo \"Error: no test specified\" && exit 1", |
| "start": "node server.js" |
| }, |
| "author": "", |
| "license": "ISC" |
| } |
# 本地包裹 => lodash
# 安裝
終端機 | PS C:\Users\user\Documents\tuts\node>npm i lodash |
| { |
| "name": "node", |
| "version": "1.0.0", |
| "description": "", |
| "main": "index.js", |
| "scripts": { |
| "test": "echo \"Error: no test specified\" && exit 1", |
| "start": "node server.js" |
| }, |
| "author": "", |
| "license": "ISC", |
| "dependencies":{ |
| "lodash": "^4.17.15" |
| } |
| } |
# 使用
| const _= require('lodash'); |
| const num = _.random(0,20); |
| console.log(num); |
| const greet = _.once(()=>{ |
| console.log('hello'); |
| }); |
| greet(); |
| greet(); |
| PS C:\Users\user\Documents\tuts\node>node server.js |
| 5 |
| Hello |