Categories
Express JavaScript Answers

How to Accept File Uploads with Express?

To accept file uploads in our Express apps, we can use the multer Express middleware.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000
const multer = require('multer');
const upload = multer({ dest: 'uploads/' })

app.get('/', (req, res) => {
  res.send('hello world')
});

app.post('/', upload.single('file'), (req, res) => {
  console.dir(req.file);
  res.send('uploaded')
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

to add the multer Express middleware.

To install it, we run:

npm i multer

Then to make the POST / route accept a file upload.

We call upload.single with the key of the form to get the file.

Then we can get the uploaded file with the req.file property.

The file will be stored in the /uploads folder as set as the value of the dest property.

Then if we make a request to the POST / route with a form data object that has the file key set to a file, the file will be uploaded.

Categories
Express JavaScript Answers

How to Call the Express res.sendFile Method with an Absolute Path?

To call the Express res.sendFile method with an absolute path, we can call the sendFile method with the root option set to the __dirname .

__dirname has the path string of the current working directory as its value.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.sendFile('public/index.html' , { root : __dirname});
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We call res.sendFile with the file path as the first argument.

It’s the path relative to the folder path set as the value of root .

root is set to __dirname , so the path in the first argument is relative to __dirname .

Categories
Express JavaScript Answers

How to Get Express to Output Nicely Formatted HTML?

To get Express to output nicely formatted HTML, we can set the app.locals.pretty property to true .

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

if (app.get('env') === 'development') {
  app.locals.pretty = true;
}

app.set('view engine', 'pug')

app.get('/', (req, res) => {
  res.render('index', { title: 'Hey', message: 'Hello there!' })
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

to prettify the HTML code returned by the Pug template engine in the dev environment with:

if (app.get('env') === 'development') {
  app.locals.pretty = true;
}

We render the response with:

res.render('index', { title: 'Hey', message: 'Hello there!' })

title and message are variables that are interpolated into the template.

In views/index.pug , we have the following template code:

html
  head
    title= title
  body
    h1= message

Now when we view the raw response, we should get:

<html>
  <head>
    <title>Hey</title>
  </head>
  <body>
    <h1>Hello there!</h1>
  </body>
</html>
Categories
JavaScript Answers Nodejs

How to Move Files in Node.js Apps?

To move files in our Node.js apps, we can use the fs.rename method.

For instance, we can write:

const fs = require('fs')

const oldPath = 'old/file.txt'
const newPath = 'new/file.txt'

fs.rename(oldPath, newPath, (err) => {
  if (err) throw err
  console.log('Successfully renamed - AKA moved!')
})

to import the fs module with:

const fs = require('fs')

Then we specify the oldPath and newPath to set the source and destination file paths respectively.

Next, we call fs.rename with the oldPath and newPath to move the file from oldPath to newPath .

The 3rd argument is a callback that will be run when the file moving operation is done.

If there’re any errors, then err will be defined.

Categories
Express JavaScript Answers

How to Set Cookies in Node Apps that Use the Express Framework?

To set cookies in Node apps that use the Express web framework, we can use the res.cookie method to set the cookie.

res.cookie will be available once we add the cookie-parse package into our app, which we can install by running:

npm i cookie-parser

For instance, we can write:

const express = require('express')
const cookieParser = require('cookie-parser');
const app = express()
const port = 3000

const options = {
  maxAge: 1000 * 60 * 15,
  httpOnly: true,
  signed: true
}

app.use(cookieParser('secret'));

app.get('/', (req, res) => {
  res.cookie('cookieName', 'cookieValue', options)
  res.send('hello world')
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We add:

app.use(cookieParser('secret'));

to add the cookieParser middleware.

The argument is the secret.

Then to add the cookie to the response of the / route, we call res.cookie with the cookie key, value, and options respectively.

maxAge is the duration that the cookie lasts.

httpOnly set to true makes the cookie accessible only by the webserver.

signed set to true indicates that the cookie should be signed with a secret.

Now when we make a request to the / route, we get the cookie back in the response.