nodejs-basic

nodejs

npm

package.json

1
{
2
    "name": "project-name",
3
    "author": "your name",
4
    "private": true,
5
    "dependencies": {},
6
    "devDependencies": {},
7
    "scripts": {
8
        "start": "node app",
9
    }
10
}

run scripts

1
$ npm run start

install module

1
# install global: -g
2
$ npm install {{module-name}} --global
3
# install local and auto save package.json dependenties.
4
$ npm install {{module-name}} --save
5
# install development only
6
$ npm install {{module-name}} --save-dev

install specific version

1
# install v4
2
$ npm install lodash@4
3
# install v4.x.x
4
$ npm install lodash@^4.0.0
5
# install v4.17.4
6
$ npm install lodash@4.17.4

use installed module

1
# use module
2
var iModule = require("module-name");

user module

exports

./random_integer.js

1
var MAX = 100;
2
3
function randomInteger() {
4
    return Math.floor(Math.random() * max);
5
}
6
7
module.exports = randomInteger;
8
//exports only one (function, array, object, string, ...)

use

1
var randomInt = require("./random-integer");
2
console.log(randomInt());

nodemon

1
# install
2
$ npm install nodemon --global
3
# run
4
$ nodemon index.js

run code by commandline

1
//in browser no require
2
if (typeof require !== 'undefined' && require.main === module) {
3
    let parameter = process.argv.slice(2)
4
}
Share