Categories
Node.js Tips

Node.js Tips — XML, MySQL, HTTP Requests, and Deleting Files

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Node.JS async.parallel

The async module is the parallel method to let us run async code in parallel.

For instance, we can write:

async.parallel({
  one(callback) {
    callback(null, 'foo');
  },
  two(callback) {
    callback(null, 'bar');
  }
}, (err, results) => {
  //...
});

We have 2 methods that take a callback in the object that we pass into async.parallel .

They both call callback with the error and result objects as the arguments.

Then we get both in the results object.

results would be:

{ one: 'foo', two: 'bar' }

The method names are used as the keys of the results.

Reading XML File in Node.js

We can read XML files in Node.js with the readFile method.

Then we can parse the content with the xml2json library.

For instance, we can write:

fs = require('fs');
const parser = require('xml2json');

fs.readFile('./data.xml', (err, data) => {
  const json = parser.toJson(data);
  console.log(json);
});

We call readFile with the path of the XML file.

Then we get the XML text with data .

Next we call parser.toJson to parse the XML string stored in data .

Node MySQL Escape LIKE Statement

We can escape the characters in a LIKE statement by writing:

mysql.format("SELECT * FROM persons WHERE name LIKE CONCAT('%', ?,  '%')", searchString)

We just concatenate the % and our searchString together.

Delete Files Older than an Hour

To get all the file older than an hour and delete them, we can use readdir to get the files in the directory.

Then we can use fs.stat to get the time and we can use that to compare with the current time to see if an hour has passed since the file has been created.

When the file is created an hour ago or earlier, we can use rimraf to delete it.

For instance, we can write:

const uploadsDir = path.join( __dirname, '/uploads');

fs.readdir(uploadsDir, (err, files) => {
  files.forEach((file, index) => {
    fs.stat(path.join(uploadsDir, file), (err, stat) => {
      let endTime, now;
      if (err) {
        return console.error(err);
      }
      now = new Date().getTime();
      endTime = new Date(stat.ctime).getTime() + 3600000;
      if (now > endTime) {
        return rimraf(path.join(uploadsDir, file), (err) => {
          if (err) {
            return console.error(err);
          }
          console.log('successfully deleted');
        });
      }
    });
  });
});

We read the folder with readdir .

Then we loop the files obtained in the callback.

Then we call fs.stat to get the file information.

We use the ctime property to get the time when the file is created.

Then we use getTime to turn it into a timestamp.

And we add 3600000 which is an hour in milliseconds.

Then if now > endTime is true , we know that more than an hour has passed since the file is created.

Then we can use rimraf to remove the file.

We use the full path.

Calling a Web Service using Node.js

We can call a web server in a Node app by making HTTP requests as we do on the client-side.

For instance, we can write:

const http = require('http');
const data = JSON.stringify({
  'id': '2'
});

const options = {
  host: 'host.com',
  port: '80',
  path: '/some/url',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json;',
    'Content-Length': data.length
  }
};

const req = http.request(options, (res) => {
  let msg = '';

  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    msg += chunk;
  });
  res.on('end', () => {
    console.log(JSON.parse(msg));
  });
});

req.write(data);
req.end();

We use the http.request method to make a request.

We call req.write to make the request with the body

The options object has the headers, hostname, and request method.

Once the request is finished, the callback is called and res has the stream with the response.

We listen to the data event to get the chunks of data and concatenated to the msg string.

Then we listen to the end event to parse the chunks that are retrieved.

Conclusion

async.parallel can run callbacks in parallel.

We can delete files with rimraf.

Also, we can make HTTP requests with the http module.

To parse XML to JSON we can use the xml2json package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *