mssql node js package not found when running azure function - node.js

I'm trying to connect SQL server inside azure function locally,
and I'm getting the following error,
[error] Worker was unable to load function timerTriggerWithEventHub: 'Error: Cannot find module 'mssql''
But I have installed mssql package in my machine,
here is my code,
const sql = require('mssql').Request;
module.exports = async function (context, myTimer) {
var config = {
user: 'sa',
password: 'Gain#123',
server: 'DESKTOP-J7IPQ7H',
database: 'RealTimeProductSales'
};
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new Request();
// query to the database and get the records
request.query('select * from dbo.ProdTC', function (err, recordset) {
if (err) console.log(err)
console.log(recordset)
// send records as a response
// res.send(recordset);
});
});
// console.log('saranraj')
// console.log(context,myTimer)
// var timeStamp = new Date().toISOString();
// if (myTimer.IsPastDue)
// {
// context.log('JavaScript is running late!');
// }
// context.log('JavaScript timer trigger function ran!', timeStamp);
// return "{'name':'saran'}"
};
when I install the package i'm getting output like this
npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\SivaSakthiVelan\package.json'
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\SivaSakthiVelan\package.json'
npm WARN SivaSakthiVelan No description
npm WARN SivaSakthiVelan No repository field.
npm WARN SivaSakthiVelan No README data
npm WARN SivaSakthiVelan No license field.
+ mssql#5.1.0
updated 1 package and audited 11650 packages in 6.832s
found 226 vulnerabilities (42 moderate, 184 high)
run `npm audit fix` to fix them, or `npm audit` for details

It seems the package.json is missing.
You can try to run the command below:
npm init -f
This command above will help you initialize a package.json (-f means force).
You can check the dependencies in your package.json.
And then run the command below:
npm install mssql

Related

Cloud Functionsdeploy (Unexpected tocken) I'm getting error (30:37 error Parsing error: Unexpected token followedUserRef) when I deploy my code

I trying to get and add documents to firestore database using clound functions (Nodejs). but I get error every time when I deploy my code.
exports.onCreateFollower = functions.firestore.document("/followers/{userId}/userFollers/{followerId}")
.onCreate((snapshot, context) => {
console.log("Follower created", snapshot.data);
const userId = context.params.userId;
const followerId = context.params.followerId;
// get followed users post
const followedUserPostRef = admin.firestore().collection('posts').doc(userId).collection('userPosts');
// get following users time line
const timelinePostRef = admin
.firestore()
.collection('timeline')
.doc(followerId)
.collection('timelinePosts');
// get the followed users posts
const querysnapshot = await followedUserPostRef.get();
// add each user posts to users timeline
querysnapshot.forEach(doc => {
if (doc.exists) {
const postId = doc.id;
const postData = doc.data();
timelinePostRef.doc(postId).set(postData);
}
});
});
i get error given below...
`
**
Running command: npm --prefix "$RESOURCE_DIR" run lint
functions# lint C:\Users\Yousuf Khan\Documents\flutter\instagram_clone\functions
eslint .
C:\Users\Yousuf Khan\Documents\flutter\instagram_clone\functions\index.js
30:37 error Parsing error: Unexpected token followedUserRef
✖ 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions# lint: eslint .
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Yousuf Khan\AppData\Roaming\npm-cache_logs\2021-04-04T07_21_32_055Z-debug.log
events.js:291
throw er; // Unhandled 'error' event
**
`
//oncreate function should be async
exports.onCreateFollower = functions.firestore.document("/followers/{userId}/userFollers/{followerId}")
.onCreate(async (snapshot, context) => {
console.log("Follower created", snapshot.data);
const userId = context.params.userId;
const followerId = context.params.followerId;
// get followed users post
const followedUserPostRef = admin.firestore().collection('posts').doc(userId).collection('userPosts');
// get following users time line
const timelinePostRef = admin
.firestore()
.collection('timeline')
.doc(followerId)
.collection('timelinePosts');
// get the followed users posts
//I have used await here
const querysnapshot = await followedUserPostRef.get();
// add each user posts to users timeline
querysnapshot.forEach(doc => {
if (doc.exists) {
const postId = doc.id;
const postData = doc.data();
timelinePostRef.doc(postId).set(postData);
}
});
});
I have used await word before followedUserPostRef.get(). so i have to make this function async. i haven't done that thats why error occure.

eslint unnecessarily warning "promise/no-nesting" with Firestore transactions

I have Firestore data structured as follows:
I want to runTransaction() on the trend_score child. My function was working prior to adding the second .then(result =>, meaning now that I added another method to the cloud function, I am getting an error:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.handler = functions.firestore.document('/Polls/{pollId}/responses/{userId}').onCreate((data, context) => {
const answerSelected = data.data().answer;
const answerRef = admin.firestore().doc(`Polls/${context.params.pollId}/answers/${answerSelected}`);
const voteCountRef = admin.firestore().doc(`Polls/${context.params.pollId}`);
const trendScoreRef = admin.firestore.doc(`Polls/${context.params.pollId}/trend_score`);
return admin.firestore().runTransaction(t => {
return t.get(answerRef)
.then(doc => {
if (doc.data()) {
t.update(answerRef, { vote_count: doc.data().vote_count + 1 });
}
})
}).then(result => {
return admin.firestore().runTransaction(t => {
return t.get(voteCountRef)
.then(doc => {
if (doc.data()) {
t.update(voteCountRef, {vote_count:doc.data().vote_count+1});
}
});
});
//starting with this set, I believe this code has caused the issue
}).then(result => {
return admin.firestore().runTransaction(t => {
return t.get(trendScoreRef)
.then(doc => {
if (doc.data()) {
t.update(trendScoreRef, {trend_score:doc.data().trend_score+1});
}
});
});
});
Error
 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions# lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/troychuinard/.npm/_logs/2018-11-10T02_02_56_229Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code1
[1]: https://i.stack.imgur.com/etVwy.png
Once you resolve the syntax error, eslint is warning you that you have nested promises. This is normally not good, but since they are nested inside a transaction callback, there's actually not a problem here. You can disable that warning at the line where eslint finds it by adding this comment to the end of the lines that it warns you about:
return t.get(answerRef) // eslint-disable-line promise/no-nesting
.then(...)

Run npm install programmatically in specified folder

I want to run npm install via typescript code in a specified directory.
I found this code:
npm.load({}, function(err: any) {
// handle errors
// install module ffi
npm.commands.install(["hello-world#0.0.1"], function(err: any, data: any) {
// log errors or data
});
npm.on('log', function(message: any) {
// log installation progress
console.log(message);
});
});
But now I don't want to install hello-world, but just run npm install (without any package).
Additionally it should run in a path that I can specify, like ./folder/subfolder
How can I do that?
Apart from exec it's also possible to use the npm package:
import * as cp from 'child_process';
var npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
var path = '/path_to_npm_install';
const result = cp.spawnSync( npm, ['install'], {
cwd: path
});
If you're using Nodejs, which I think you are, you can run
child_process.exec('npm install') // or any other command which you give from terminal or command prompt
Check the documentation for child_process
https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
You can create a nodejs script that expect the directory path from user and create a child process and execute that command in that.
index.js
const { exec } = require('child_process');
exec(`cd /${process.env.PATH} | npm install`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
PATH=/path_of_directory_to_run_npm_install node index.js
Read more about child_process from nodejs documentation - https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

Update NPM modules from within grunt

I'm trying to automate the update of new node modules but, npm update seems not to want to run correctly from within grunt also updating the package.json file with the new version. I want to do this regardless of what version is specified in the package.json file.
What I found till now is the node module: npm-check-updates (https://www.npmjs.com/package/npm-check-updates)
The problem is that I can't get it to work with other modules like npm-shell or npm-exec.
I've tried using npm update -D directly, but that fails too.
I'm asking if it can be done.
Here's what I use:
grunt.registerTask('update', 'Update npm modules', function() {
var exec = require('child_process').exec;
var cb = this.async();
exec('npm update -D', {}, function(err, stdout) {
console.log(stdout);
cb();
});
});
If i'm correct you're trying to update ALL of your npm packages inside of your package.json file? I would recommend using this package.
Install the package.
npm install grunt-auto-install --save-dev
Add it to your grunt tasks.
grunt.loadNpmTasks('grunt-auto-install');
Then add the configuration to your gruntfile.js
grunt.initConfig({
auto_install: {
local: {},
subdir: {
options: {
cwd: 'subdir',
stdout: true,
stderr: true,
failOnError: true,
npm: '--production'
}
}
},
});
Here is the reference:
https://www.npmjs.com/package/grunt-auto-install
AFTER YOUVE UPDATED THE PACKAGES
Update your devDependencies and dependencies automatically with a grunt task.
Install the npm module to update your packages in your dev dependencies object.
npm install --save-dev grunt-dev-update
Add it to your grunt tasks.
grunt.loadNpmTasks('grunt-dev-update');
Add your configuration to your gruntfile.
devUpdate: {
main: {
options: {
//task options go here
}
}
}
Reference:
https://www.npmjs.com/package/grunt-dev-update
I found a solution using npm-check-update (ncu) and grunt.util.spawn:
// Install NPM Updates
grunt.registerTask('update-npm', 'Update package.json and update npm modules', function() {
grunt.log.writeln('If you get an error here, run "npm install -g npm-check-updates".');
grunt.task.run('npm-write-new');
grunt.task.run('npm-update');
});
// Check for npm module updates
grunt.registerTask('npm-check', 'Check for npm modules updates', function() {
var done = this.async();
grunt.log.writeln('Checking for npm modules updates ...');
grunt.util.spawn({
cmd: 'ncu',
args: '',
opts: {
stdio: 'inherit',
}
}, function () {
grunt.log.writeln('No files were modified.');
done();
});
});
// Write new versions to packages.json
grunt.registerTask('npm-write-new', 'Write new versions to package.json', function() {
var done = this.async();
grunt.log.writeln('Checking for npm modules updates ...');
grunt.util.spawn({
cmd: 'ncu',
args: ['-u'],
opts: {
stdio: 'inherit',
}
}, function () {
grunt.log.writeln('New versions were written to "package.json".');
done();
});
});
// Update npm modules
grunt.registerTask('npm-update', 'Update npm modules', function() {
var done = this.async();
grunt.log.writeln('Installing npm modules updates ...');
grunt.util.spawn({
cmd: 'npm',
args: ['update','--loglevel','warn'],
opts: {
stdio: 'inherit',
}
}, function () {
grunt.log.writeln('NPM modules were updated.');
done();
});
});

Mocking file system contents not working with gulp.src

I'm trying to use mock-fs to mock up file system contents to test gulp tasks. Unfortunately, gulp.src doesn't seem to play well with mock-fs. Specifically, I get ENOENT errors:
Message:
ENOENT, lstat '/vagrant/study-node-heroku/instances/development/app.json'
Details:
errno: -2
code: ENOENT
path: /vagrant/study-node-heroku/instances/development/app.json
domainEmitter: [object Object]
domain: [object Object]
domainThrown: false
Stack:
Error: ENOENT, lstat '/vagrant/study-node-heroku/instances/development/app.json'
at Error (native)
Other parts of my code and test code access the mock-fs-created files just fine.
What am I doing wrong? I suspect that the problem is related to gulp's usage of vinyl.
Here is the function under test:
var herokuTarball = function(options, done) {
var instance = options.instance || 'development';
var tarballName = options.tarballName || instance
var tarballPath = path.join(config.temp, tarballName + '.tar.gz');
var files = path.join(config.instances, instance, '**/*');
yassert.file(path.join(config.instances, instance, 'app.json'));
async.waterfall([
function(cb) {
del([tarballPath], cb);
},
function(err, cb) {
gulp.src(files)
.pipe(tar(tarballName + '.tar'))
.pipe(gzip())
.pipe(gulp.dest(config.temp))
.pipe(gcallback(cb));
}
], function(err, result) {
if (err) return err;
return done(err, tarballPath);
});
}
And here is the test snippet:
describe('gulp heroku:tarball', function() {
after('something', function() {
mock.restore();
});
before('something', function() {
mock({
'instances/development': {
'app.json': 'test content'
}
});
});
it('creates a tarball', function(done) {
var options = {}
heroku.herokuTarball(options, function(err, result) {
expect(result).to.be.a('string');
yassert.file(result);
done();
});
});
});
Notice that the yassert (yeoman-assert) calls pass fine -- the file is there. If I take the function with the gulp.src call out of the async waterfall, the error goes away (and the test fails of course).
Issue posted at https://github.com/tschaub/mock-fs/issues/44
You are not doing anything wrong, mock-fs README states:
Note mock-fs is not compatible with graceful-fs#3.x but works with graceful-fs#4.x.
Looking at the dependencies of gulp we get:
$ npm info gulp devDependencies.graceful-fs
^3.0.0
Hence, gulp is still dependent on graceful-fs#3.x, therefore mock-fs will not work.
YMMV, but maybe vinyl-fs-mock is an alternative?

Resources