Framework/Node.js

노드.제이에스 기본 내장 함수 Node.js Fundamental

청렴결백한 만능 재주꾼 2021. 4. 30. 00:22
반응형

//__dirname - pwd 느낌, 현재 위치(경로) - path to current directory

// __filename - file name

// require - 모듈을 사용하기 위한 함수 function to use modules(CommonJS)

// module - 현재 모듈에 대한 인포 info about current module (file)

// process - 프로그램이 실행 되는 환경변수의 인포 info about env where the program is being executed

 

 

//names.js

const secret = 'SUPER SECRET'
const john = 'john'
const peter = 'peter'


module.exports = {john,peter}

 

 

console.log(module) 한 결과

 

 

 


 

 

 

//utils.js

const sayHi = (name)=> {
    console.log(`Hello there ${name}`)
}

module.exports = sayHi

console.log(module) 한 결과

 

 


 

 

//alternative-flavor.js

module.exports.items = ['item1','item2']
const person = {
    name: 'bob',
}

module.exports.singlePerson = person



//mind-grenade.js

const num1 =5;
const num2 = 10;

function addValues() {
    console.log(`the sum is : ${num1 + num2}`)
}

addValues()

alternative-flavor.js module 출력 화면

 

 

 

 


 

 

 

 

//os-module.js
const os = require('os')

// info about current user
const user = os.userInfo()
console.log(user)

// method returns the system uptime in seconds
console.log(`The System Uptime is ${os.uptime()/60/60/24} days`);

const currentOS = {
    name: os.type(),
    release:os.release(),
    totalMem: os.totalmem(),
    freeMem: os.freemem(),
}

console.log(currentOS)

 

os-module.js 출력 화면 

 

 

 


 

 

 

//9-path-module.js

const path = require('path')

console.log(path.sep)

const filePath = path.join('/content','subfolder','test.txt')
console.log(filePath)

const base = path.basename(filePath)
console.log(base)

const absolute = path.resolve(__dirname,'content','subfolder','test.txt')
console.log(absolute)

 

9-path-module.js 출력 화면

 

 

 


 

 

 

//fs-sync.js
const {readFileSync, writeFileSync} = require('fs') 
console.log('start')
const first = readFileSync('./content/first.txt', 'utf8');
const second = readFileSync('./content/second.txt', 'utf8');

writeFileSync(
    './content/result-sync.txt',
    `Here is the result : ${first}, ${second}`
    ,
    {flag : 'a'}
)
console.log('done with this task')
console.log('starting the next one')




//-----------------------------------------
//fs-async.js

const { readFile, writeFile } = require('fs')

console.log('start')
readFile('./content/first.txt', 'utf8', (err, result) => {
    if (err) {
        console.log(err)
        return
    }
    const first = result;
    readFile('./content/second.txt', 'utf8', (err, result) => {
        if (err) {
            console.log(err)
            return
        }
        const second = result;
        writeFile(
            './content/result-async.txt',
            `Here is the result : ${first}, ${second}`,
            (err, result) => {
                if (err) {
                    console.log(err)
                    return
                }
                console.log('done with this task')
            })
    })
})
console.log('starting the next one')

 

왼쪽)fs-sync.js  오른쪽)fs-async.js 

 

 


http 모듈을 가져와 server를 연다. 5000포트를 사용하고 

console.log(req)를 하면 어마어마한 양의 정보가 뜬다. 

req중의 url를 가져와 구분하여 페이지를 안내한다.

 

//http.js

const http = require('http');

const server = http.createServer((req, res, err) => {
    if(req.url === '/'){
        res.end('Welcome to our home page')
    }
    else if(req.url === '/about'){
        res.end('Here is our short history')
    }else{
    res.end(`
    <h1>Opps!</h1>
<p>We can't seem to find the page you are looking for</p>
<a href="/">back home</a>
`)} 
})

server.listen(5000)

 

 

 

 


 

node.js package manager

NPM

// npm - global command, comes with node

// npm --version 

 

 

// local dependency - use it only in this particular project

// npm i <packageName>

 

//global dependency - use it in any project

// npm install -g <packageName>

// sudo install -g <packageName> (mac)

 

//package.json - manifest file (stores important info about project/package)

// manual approach (create package.json in the root, create properties etc)

//npm init (step by step, press enter to skip) - 패키지 이름, 등등 을 설정함.

//npm init -y (everything default)

반응형