Riyota Miyagi
Riyota Miyagi

Reputation: 19

Save filename on database automatically Using Nodejs

I'm having trouble with NodeJS. I want to create a server-side script that will get a new file's filename to its directory and save it to database automatically.

here is my code:

const path = require('path')

//mysql Connecion
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "sms"
});

//con checking if the database is connected
con.connect(function(err) {
    if (err) throw err;

    //watchfile directory if there's new added file
    var chokidar = require('chokidar'); 
    var watcher = chokidar.watch('texts/', {ignored: /^\./, persistent: true});

    //for getting the filename only
    var fs = require('fs');
    var testFolder = 'texts/';

    watcher.on('add', function(filePath) {

        var filename = path.basename(filePath);

        var selectSql = 'SELECT count(filename) AS matchingEntriesCount FROM txtfilename WHERE filename="${filename}"';
        con.query(selectSql, (err, results, fields) => {
            // TODO: Catch the error
            console.log(err);
            var matchingEntriesCount = results[0].matchingEntriesCount

            if (matchingEntriesCount == 0) {
                console.log('File', filename, 'has been added');
                // TODO: Do your insert query
                var insertsql = "INSERT INTO txtfilename (filename) VALUES ('"+ filename +"')";
                con.query(insertsql, function (err, result) {
                    if (err) throw err;
                    console.log("1 record inserted");
                });

            }
        });
    });

});

hopefully, someone will help me with my problem.. thank you.

Upvotes: 0

Views: 90

Answers (1)

Mansuro
Mansuro

Reputation: 4627

watcher is a local variable to the function connect so it is deleted when exiting the function. If you want your code to work, you need to make watcher a global var.

The connection is established implicitly anyway when you call con.query, so you could remove con.connect altogether.

Upvotes: 1

Related Questions