Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to retrieve value from sql server and offer the user a text file download with the value

I am getting a value from SQL Server. After that I try to offer a text file download to the user with the content being the value I retrieve from the database. Through a query string I pass the ID value (http://localhost:8080/index.js?ID=1).

Setting the text variable at the bottom with the database value is not possible. How can I export the database value to text file in this scenario?

const http = require('http');
const url = require('url');
const sql = require('mssql');

// config info database
const config = {
    user:       'test_user',
    password:   '123',
    server:     'localhost',
    database:   'TestDatabase',
    port:       1433,
    trustServerCertificate: true,
};

http.createServer(function (req, res) {
    const queryObject = url.parse(req.url, true).query.ID;

    // connect to database
    sql.connect(config, function (err) {

        if (err) console.log(err);

        // create a new Request object
        let sqlRequest = new sql.Request();

        // query the database and get data in the data Object
        let sqlQuery='SELECT Testvalue FROM TestDatabase.dbo.TestTable WHERE ID = ' + queryObject;
        sqlRequest.query(sqlQuery, function (err, data) {

            if (err) console.log(err)

            // display the data in the console
            //console.table(data.recordset[0].Testvalue);
            text = "This is a content of a txt file. Value from database = " + data.recordset[0].Testvalue;

            // close the connection
            sql.close();

        });
    });

    text = 'how do I get the value in here from the database??';
    res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':'attachment; filename=file.txt'});
    res.end(text);

}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Looks to me like you just have to move your res.writeHead... and res.end... into the code block where you get the text from the database – try just after sql.close();

That’s assuming your sql works.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading