Categories
Express JavaScript Answers

How to Serve a Single Static File with Express.js?

To serve a single static file with Express.js, we can use the express.static middleware.

For instance, we can write:

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

app.use("/foo.txt", express.static(__dirname + '/foo.txt'));

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

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

to add:

app.use("/foo.txt", express.static(__dirname + '/foo.txt'));

to use the express.static middleware to expose the foo.txt file to the public.

We make it accessible by making a request to “/foo.txt” since that’s the first argument we passed into app.use .

And we make it serve the foo.txt file from the current working directory with:

express.static(__dirname + '/foo.txt')

So when we make a request to /foo.txt , we would see its contents in the response.

Categories
Express JavaScript Answers

How to Generate robots.txt in Express?

To generate a robots.txt file from our Express app, we can create a robots.txt file that returns the text content of the robots.txt file.

For instance, we can write:

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

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

app.use('/robots.txt', function(req, res, next) {
  res.type('text/plain')
  res.send("User-agent: *\nDisallow: /");
});

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

to create the /robots.txt route by writing:

app.use('/robots.txt', function(req, res, next) {
  res.type('text/plain')
  res.send("User-agent: *\nDisallow: /");
});

We call res.type to set the MIME type of the response to text/plain .

And we call res.send with the robots.txt content we want to return.

So when we make a GET request to the /robots.txt route, we get:

User-agent: *
Disallow: /
Categories
Express JavaScript Answers

How to Add Response Timeout Feature to an Express.js App?

To add a response timeout feature to an Express.js app to end requests that take too long to process, we can use the connect-timeout package.

To install it, we run:

npm i `connect-timeout`

Then we can use it by writing:

const express = require('express')
const timeout = require('connect-timeout');
const app = express()
const port = 3000
const haltOnTimedout = (req, res, next) => {
  if (!req.timedout) {
    next();
  }
}

app.use(timeout(120000));
app.use(haltOnTimedout);

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

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

We include the module with require .

Then we create the haltOnTimeout function that checks the req.timedout property to see if the request has timed out.

If it hasn’t timed out, then req.timedout is false and we call next to move forward with the request.

This property is available which we added:

app.use(timeout(120000));

to add the connect-timeout middleware to detect the timeout.

120000 is in milliseconds and it’s the number of milliseconds before the request times out.

Categories
Express JavaScript Answers

How to Accept form-data Request Data with Express?

To accept form-data request data in our Express app, we can use the body-parser package.

To install it, we run:

npm i body-parser

Then we can use it by writing:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3000

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/', (req, res) => {
  res.send(req.body)
});

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

so that we can accept form-data requests in our Express app.

We call bodyParser.urlencoded to accept form-data requests.

The extended option lets us choose between parsing the URL-encoded data with the querystring library with its set to false or the qs library when it’s set to true .

Therefore, when we make a x-www-form-urlencoded request with some key-value pairs, we should get them in the req.body object.

So we’ll see them returned as the response when we make a POST request to the / route.

Categories
JavaScript Answers Nodejs

How to Convert CSV to JSON in Node.js?

To convert CSV to JSON in our Node.js apps, we can use the csvtojson library.

To install it, we run:

npm i csvtojson

Then we if have the following in sample.csv :

a,b,c,d
1,2,3,4
5,6,7,8

then we can convert the CSV file content into a JSON object by writing:

const csv = require("csvtojson");
const csvFilePath = './sample.csv'

const convertToJson = async (csvFilePath) => {
  const jsonArrayObj = await csv().fromFile(csvFilePath)
  console.log(jsonArrayObj);
}

convertToJson(csvFilePath)

We have the convertToJson function that takes a csvFilePath .

Then we call csv().fromFile with it to convert the CSV file content into a JSON object and assign that to jsonArrayObj .

As a result, jsonArrayObj is:

[
  { a: '1', b: '2', c: '3', d: '4' },
  { a: '5', b: '6', c: '7', d: '8' }
]

when we call it.