Reputation: 5174
I am writing a script that checks for JSON files in a directory and updates a MongoDB collection with documents containing the data found in those files.
I want to check if a file has been changed since it was last used to update a document.
At the moment, I am using this code to check for JSON files/read their content:
import fs from 'fs'
fs.readdir(`../Items`, (err, files) => {
if (err) console.error(err)
files = files.filter((file) => file.split('.').pop() === 'json')
if (files.length <= 0) return console.error('No items to process!')
files.forEach((file, i) => {
fs.readFile(`../Items/${file}`, (err, data) => {
if (err) return console.error(err)
console.log(data)
})
})
})
I think finding out the file's last modified date and its MD5 hash would be the way to do it but I am not sure how to get those using fs.
Upvotes: 1
Views: 967
Reputation: 2939
I recommend to check if file content is changed using Hash. It's much more reliable where whenever file content changes, the hash is also changes. This piece of code could help you. Hope it helpful.
const crypto = require('crypto')
const fs = require('fs')
const fileContent = fs.readFileSync('./uploadedFile.json', { encoding: 'utf-8' })
const fileUploadedHash = crypto.createHash('md5').update(fileContent).digest('base64');
if(fileUploadedHash !== existingFileHash) {
// update data in MongoDB
}
Upvotes: 2
Reputation: 1472
You can do this by using the mtime attribute from the stat function. See more here at attacomsian
const fs = require('fs');
// fetch file details
fs.stat('file.txt', (err, stats) => {
if(err) {
throw err;
}
// print file last modified date
console.log(`File Data Last Modified: ${stats.mtime}`);
console.log(`File Status Last Modified: ${stats.ctime}`);
});
Upvotes: 2