I'm trying to execute a stored procedure and when I run the code below, the code in the function for the query is not being run at all. There is also no error. I am thinking somehow SQL Server is interpreting the query for the stored procedure incorrectly and stalling because if I use a regular query e.g. select top 1 * from Custom.ExampleTable it works fine.
var express = require('express');
var app = express();
const sql = require("mssql/msnodesqlv8");
// example db connection...
const connectionString = "server=dev\\instance1;database=123456;user=ORG\\NAME;Trusted_Connection=Yes;"
sql.connect(connectionString, err => {
console.log("connected: " + connectionString)
try {
new sql.Request().input('var', sql.VarChar, 2222).execute('dbo.check_ex', (err, results) => {
// code not being run...
console.dir("test")
if (err) {
console.log(err);
}
console.log(rows);
})
} catch (err) {
console.log(err);
}
})
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Output below:
Server is running..
connected: server=dev\\instance1;database=123456;user=ORG\\NAME;Trusted_Connection=Yes;
Related
I'm new to Node and have previously just written Javascript for simple browser extensions. What I'm trying to do is run a shell script and then return the text for it on a get request (simplified version).
I've tried looking at callbacks and can't seem to get my head around it or even adapt another example to what I'm trying to do. My main problem is either that the I'm receiving the error "first argument must be one of type string or buffer. received type undefined" or "received type function" (when I tried to implement a callback, which is what I believe I need to do here?).
I've looked at a few examples of callbacks and promises and seeing them in abstraction (or other contexts) just isn't making sense to me so was hoping someone could help direct me in the right direction?
The code is very crude, but just trying to get some basic functionality before expanding it any further.
var express = require("express");
var app = express();
const { exec } = require("child_process");
var ifcfg = function(callback) {
exec("ifconfig", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return error;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return err;
} else {
var output = stdout.toString();
return callback(output);
}
});
}
app.get("/ifconfig", (req, res) => res.write(ifcfg(data)));
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
});
In JavaScript, a callback is a function passed into another function as an argument to be executed later.
Since the command is executed asynchronously you will want to use a callback to handle the return value once the command has finished executing:
var express = require("express");
var app = express();
const { exec } = require("child_process");
function os_func() {
this.execCommand = function(cmd, callback) {
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
callback(stdout);
});
}
}
app.get("/", (req, res) => {
console.log("InsideGetss");
var os = new os_func();
os.execCommand('ifconfig', function (returnvalue) {
res.end(returnvalue)
});
});
Hello i'm trying to fetch some partner names from my mongodb database and put them into a list of variables. But it for some reason loses it's definition when I try to export it. What's going on?
This is the first file.
///// mongodb.js /////
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const findDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('partners');
// Find some documents
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
callback(docs);
});
};
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'yarle';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected succesfully to Database");
const db = client.db(dbName);
findDocuments(db, function(docs) {
module.exports = {
partner1: console.log(docs[0]['partner_name']),
partner2: console.log(docs[1]['partner_name']),
partner3: console.log(docs[2]['partner_name']),
};
client.close();
});
});
//console.log(Object.keys(partners[0][0]));
And this is the end file.
///// Endfile.ts /////
import { Request, Response } from 'express';
import { PartnersList } from './data.d';
var partners = require( './mongodb.js');
console.log(partners.partner1);
const titles = [
partners.partner1,
partners.partner2,
partners.partner3,
];
Your problem is not with module.exports, it's with asynchronous programming. When you call MongoClient.Connect, the code in your callback does not get executed synchronously. It gets executed some time in the future. You have no control over when that happens.
The same thing is true of the findDocument callback.
Programming asynchronously is a little trickier, but you will have to learn it to write modern javascript. Asynchrony is a central tenet of nodejs. Read on it, learn examples, and your problem will become clear.
Instead of exporting the values of partner1, 2 and 3, export a function with a callback. This new function can call MongoClient.Connect, passing down the callback. Endfile.ts can now call your newly created asynchronous function and assign the titles array in the callback.
Like this:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const findDocuments = function (db, callback) {
// Get the documents collection
const collection = db.collection('partners');
// Find some documents
collection.find({}).toArray(function (err, docs) {
assert.equal(err, null);
callback(docs);
});
};
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'yarle';
module.exports.getPartners = (callback) {
// Use connect method to connect to the server
MongoClient.connect(url, function (err, client) {
if (err) {
callback(err);
return;
}
console.log("Connected succesfully to Database");
const db = client.db(dbName);
findDocuments(db, function (docs) {
const partners = {
partner1: docs[0]['partner_name'],
partner2: docs[1]['partner_name'],
partner3: docs[2]['partner_name']
};
callback(null, partners);
client.close();
});
});
}
and this
import { Request, Response } from 'express';
import { PartnersList } from './data.d';
var mongoClient = require('./mongodb.js');
mongoClient.getPartners(function (err, partners) {
assert.equal(null, err);
const titles = partners;
});
I have a table in sql Server and I am trying to display it in web browser and apply datatable(jQuery) to it. Below code works fine as it gives the output in command line. But I'd have to get it on the browser(probably in json format).
I am using 'tedious' for connection as that's what I found in Express.js documentation.
var express = require('express');
var app = express();
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var config = {
userName: 'clientinfo',
password: 'clientinfo123',
server: 'USW20051234'
}
var connection = new Connection(config);
connection.on('connect', function (err) {
if (err) {
console.log(err);
} else {
executeStatement();
}
});
function executeStatement() {
request = new Request("SELECT * from dbo.Logs", function (err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount+' rows');
}
connection.close();
});
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log(JSON.stringify(column.value));
}
});
});
connection.execSql(request);
}
You need to start HTTP server. As you already define APP try this
app.get('/urltest', (req, res) => {
res.send('hello from nodejs');
});
const PORT = 5000;
app.listen(PORT);
console.log('Listening on :' + PORT + '...');
and try http:localhost:5000/urltest on a browser
Thank You everyone for all the suggestions. I think "tedious" was giving me a hard time so I did npm install mssql and that worked like a charm.
Below is the link I referred to.
http://www.tutorialsteacher.com/nodejs/access-sql-server-in-nodejs
The code is set up this way:
var express = require('express');
var router = express.Router();
var mongo = require('mongodb').MongoClient;
function getData(){
db.collection("collection_name").find({}).toArray(function (err, docs) {
if (err) throw err;
//doing stuff here
}
var dataset = [
{//doing more stuff here
}
];
});
}
router.get("/renderChart", function(req, res) {
mongo.connect(url_monitor, function (err, db) {
assert.equal(null, err);
getData(res);
});
});
When I run the code and trying to get to /renderChart when running, I get the "ReferenceError: db is not defined". I came across a similar case, and think it may be a similar problem caused because mongodb.connect() is called asynchronously, but I couldn't get it to work:
Express js,mongodb: "ReferenceError: db is not defined" when db is mentioned outside post function
The problem here is you don't pass the db to the function, so it's undefined.
A solution:
function getData(db, res){
db.collection("collection_name").find({}).toArray(function (err, docs) {
if (err) throw err;
//doing stuff here
}
var dataset = [
{//doing more stuff here
}
];
});
}
router.get("/renderChart", function(req, res) {
mongo.connect(url_monitor, function (err, db) {
assert.equal(null, err);
getData(db, res);
});
});
You'll probably need to pass the req at some point too, or make specific db queries. And you'll probably want to use promises or async/await to better deal with all asynchronous calls.
Its Simple Javascript.
You are using a variable db in your file, which is not defined, so it will throw an error.
You need to do something like this .
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Find some documents
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
assert.equal(2, docs.length);
console.log("Found the following records");
console.dir(docs);
callback(docs);
});
}
I have the same problem before, instead of passing db to routing function, My solution is to make db variable global like
var mongojs = require('mongojs')
global.db = mongojs(<mongodb url>);
then db variable can be used in any part of your code
If you're using express, put that in your app.js file and you will never have to worry about db variable anyore.
PS: some people think that using global is not a good practices, but I argue that since global is a node.js features and especially since it works, why not
node.js global variables?
You don't have tell the codes, that which database you want to use.
how to get databases list https://stackoverflow.com/a/71895254/17576982
here is the sample code to find the movie with name 'Back to the Future' in database sample_mflix > collection movies:
const { MongoClient } = require("mongodb");
// Replace the uri string with your MongoDB deployment's connection string.
const uri =
"mongodb+srv://<user>:<password>#<cluster-url>?retryWrites=true&writeConcern=majority";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// Query for a movie that has the title 'Back to the Future'
const query = { title: 'Back to the Future' };
const movie = await movies.findOne(query);
console.log(movie);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
to get list of database, put await client.db().admin().listDatabases() on fun function. e.g.
async function run() {
try {
await client.connect();
var databasesList = await client.db().admin().listDatabases();
console.log("Databases:");
databasesList.databases.forEach(db => console.log(` - ${db.name}`));
learn MongoDB more from official docs: https://www.mongodb.com/docs
I have created an application using Node.js to connect with SQL Server. Below is the code:
app.get('/SalesStatistics', function (req, res) {
var Connection = require('tedious').Connection;
// config for your database
var config = {
user: "****",
password: "*****",
server: "abc",
database: "xyz"
};
var connection = new Connection(config);
connection.on('connect', function (err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement();
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement() {
request = new Request("select * from employee;", function (err) {
if (err) {
console.log(err);
}
});
var result = "";
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
result += column.value + " ";
}
});
console.log(result);
result = "";
});
request.on('done', function (rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}
});
Received the below error in console:
message: 'Requests can only be made in the LoggedIn state, not the Connecting state'
code: EIINVALIDSTATE
Also tried the sample from Github site, but still I could not connect to SQL Server. Please let me know if any other possibility.
I just encountered the same problem awhile ago running the same code above with similar environment.
It turn out that I did not configure the sql server (using Sql Server Management Manager) to accept TCP connection to port (1433). After I done that, everything work fine.