Closed dangvanthanh closed 11 months ago
const fs = require('fs')
let content
try {
content = fs.readFileSync('file.md', 'utf-8')
} catch (e) {
console.log(e)
}
console.log(content)
const fs = require('fs')
console.log('Start reading a file')
fs.readFile('file.md', 'utf-8', function (err, content) {
if (err) {
console.log('Error happened during reading the file')
return console.log(err)
}
console.log(content)
})
http
module for Node.js serverconst http = require('http')
const port = 3000
const requestHandler = (req, res) => {
if (req.url === '/') {
res.end('Welcome')
}
if (req.url === '/hello') {
res.end('Hello')
}
}
const server = http.createServer(requestHandler)
server.listen(port, err => {
if (err) {
return console.log('Something bad happened', err)
}
console.log(`Server is listening on ${port}`)
})
The http
module is very low-level. Creating a complex web application web using the snipper above is very time-consuming. This is a reason why we usually pick a framework with for our project. The popular framework.
A sample using Express and Pug. The first, we need install Express and Pug:
$ npm install express --save
$ npm install pug --save
|__ index.js
|__ views
|__ index.pug
|__ hello.pug
Populate index.js
such as:
const path = require('path')
const express = require('express')
const app = express()
const port = 3000
app.set('view engine', 'pug')
app.set('views', path.join(__dirname, 'views'))
app.get('/', (req, res) => {
res.render('index', {
title: 'Template',
message: 'Express and Pug Template'
})
})
app.get('/hello', (req, res) => {
res.render('hello', {
title: 'Hello',
name: 'Dang Van Thanh'
})
})
app.listen(port, (err) => {
if (err) {
return console.log('Something bad happened', err)
}
console.log(`Server is listening on ${port}`)
})
Nunjucks is a rich and powerful templating language for JavaScript. And Nunjucks familiar HTML than Pug.
$ npm install nunjucks --save
const nunjucks = require('nunjucks')
const express = require('express')
nunjucks.configure('views', {
express: app,
autoescape: true
})
app.set('view engine', 'html')
app.get('/', (req, res) => {
res.render('index.html')
})
const express = require('express')
const app = express()
app.use('/static', express.static('public'))
You can set up a Node.js application databases and using it. Below some way you can storing data:
const users = []
app.post('/users', (req, res) => {
users.push({
name: 'Dang Van Thanh',
age: 30
})
res.send('Successfully registered')
})
Using this methods might be problematic for several reasons:
const fs = require('fs')
app.post('/users', (req, res) => {
fs.appendToFile(
'user.txt',
JSON.stringify({ name: 'Dang Van Thanh', age: 30 }),
err => {
res.send('Sucessfully registered')
}
)
})
This method still has a couple of flaws:
$ npm install pg --save
You can interact with PostgreSQL via Node.js such as:
const express = require('express')
const { Client } = require('pg')
const connectionString = 'postgres://dangvanthanh@localhost/learning_objectives'
const client = new Client({
connectionString: connectionString
})
const app = express()
const port = 3000
// Insert record to `users` table in `learning_objectives` database
app.post('/users', (req, res, next) => {
let user = {}
user.name = 'Dang Van Thanh '
user.age = 30
client.connect()
client.query(
'INSERT INTO users (name, age) VALUES ($1, $2);',
[user.name, user.age],
(err, result) => {
if (err) {
console.log(err)
}
res.send(200)
}
)
})
// Query all records from `users` table in `learning_objectives` database
app.get('/users', (req, res, next) => {
client.connect()
client.query('SELECT name, age FROM users;', [], (err, result) => {
if (err) {
console.log(err)
}
res.json(result.rows)
})
})
app.listen(port, err => {
if (err) {
return console.log('Something bad happened', err)
}
console.log(`Server is listening on ${port}`)
})
HTTP stands for Hypertext Transfer Protocol
. HTTP functions as a request-response protocol in the client-server computing model
Status Codes | Description | Most Common |
---|---|---|
1xx | Informational | |
2xx | Success | Success codes are 200 OK , 201 Created and 204 No Content |
3xx | Redirection | Redirection codes are 301 Moved Permanently , 304 Not Modified |
4xx | Client Error | Client error codes are 400 Bad Request , 401 Unauthorized , 403 Forbidden , 404 Not Found , 409 Conflict |
5xx | Server Error | Server error codes are 500 Internal Server Error , 503 Service Unavailable |
Create a small Express application that can render the current weather conditions based on city names using AccuWeather API
const path = require('path')
const nunjucks = require('nunjucks')
const express = require('express')
const rq = require('request-promise')
const app = express()
const port = 3000
nunjucks.configure('views', {
express: app,
autoescape: true
})
app.set('view engine', 'html')
app.set('views', path.join(__dirname, 'views'))
app.use('/static', express.static('public'))
app.get('/:city', (req, res) => {
rq({
uri: 'http://apidev.accuweather.com/locations/v1/search',
qs: {
q: req.params.city,
apiKey: 'hoArfRosT1215'
},
json: true
})
.then(data => {
const city = {
name: data[0].EnglishName,
geo: {
lat: data[0].GeoPosition.Latitude,
long: data[0].GeoPosition.Longitude
}
}
res.render('index.html', { city: city } )
})
.catch(err => {
console.log(err)
res.render('error.html')
})
})
app.listen(port, err => {
if (err) {
return console.log('Something bad happened', err)
}
console.log(`Server is listening on ${port}`)
})
Beginner Node.js