Update NPM modules from within grunt - node.js

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();
});
});

Related

how to connect sqlite3 with electron js

please guide me through a full process, that I connect my electron app with sqlite3.
because I have a lot of issues occurring in my electron js.
Thank you.
Main.js:
const{app,BrowserWindow,ipcMain}=require("electron");
app.on("ready",createWindow);
const si = require("systeminformation");
require("electron-reload")(__dirname);
function createWindow()
{
const window = new BrowserWindow({
width: 800,
height:600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
});
window.webContents.openDevTools();
window.loadFile(__dirname+ "/index.html");
}
ipcMain.on("get-cpu-usage",(events,args)=>{
console.log(args);
});
renderer.js:
const{ipcRender} = require("electron")
const os=require("os");
const cpuName=document.getElementById("cpu-name");
const cpuCores =document.getElementById("cores");
const cpuUsage =document.getElementById("cpu-usage");
const cpus=os.cpus();
cpuName.innerText=`CPU: ${cpus[0].model}`;
cpuCores,innerText=`Cores Available: ${cpus.length}`;
setInterval(() =>{
console.log("sending message to get cpu stats")
ipcRender.send("get-cpu-usage", "Hello sheraz The render process")
},2000)
By far the easiest way to use SQLite with electron is with electron-builder.
First, add a postinstall step in your package.json:
"scripts": {
"postinstall": "install-app-deps"
...
}
and then install the necessary dependencies and build:
npm install --save-dev electron-builder
npm install --save sqlite3
npm run postinstall
electron-builder will build the native module for your platform, with the correct name for the Electron binding; and you can then require it in code as normal.

mssql node js package not found when running azure function

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

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

How do I run Jest Tests

I have following hello World test to my __tests__ folder:
hello-test.js:
describe('hello world', function() {
it('basic test', function() {
expect(1).toBe(1);
});
});
My aim is to eventually write tests in es6 and run using a gulp task. I have tried running the above with the following gulp task:
gulp.task('jest', ['test-compile'], function(done){
jest.runCLI({
rootDir : __dirname,
//scriptPreprocessor : "../node_modules/babel-jest",
testFileExtensions : ["es6", "js"],
}, __dirname, function (result) {
if (result) {
console.log(result);
} else {
console.log('Tests Failed');
}
done();
});
});
I have also tried running jest using the globally install jest-cli and cannot get it to work, I also tried using the npm test way as shown on line but no matter which of these I try I just get Using Jest CLI v0.6.0 in the terminal, no errors no results.
I am very confused as I seem to be doing what all the doc's online say. I am using Node 4.2.1 if that has any bearing

Running node app from grunt with watch

So, I have the grunt file below. I'm wanting to add a task that will start my node app and watch for changes in a directory and restart. I have been using supervisor, node-dev (which are great) but I want to run one command and start my whole app. There has got to be a simple way to do this, but I'm just missing it. It is written in coffeescript as well (not sure if that changes things)...
module.exports = function(grunt) {
grunt.initConfig({
/*exec: {
startApi: {
command: "npm run-script start-api"
}
},*/
//static server
server: {
port: 3333,
base: './public',
keepalive: true
},
// Coffee to JS compilation
coffee: {
compile: {
files: {
'./public/js/*.js': './src/client/app/**/*.coffee'
},
options: {
//basePath: 'app/scripts'
}
}
},
mochaTest: {
all: ['test/**/*.*']
},
watch: {
coffee: {
files: './src/client/app/**/*.coffee',
tasks: 'coffee'
},
mochaTest: {
files: 'test/**/*.*',
tasks: 'mochaTest'
}
}
});
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-mocha-test');
//grunt.loadNpmTasks('grunt-exec');
grunt.registerTask( 'default', 'server coffee mochaTest watch' );
};
As you can see in the comments, I tries grunt-exec, but the node command stops the execution of the other tasks.
You can set grunt to run default task and the watch task when you start your node app:
in app.js
var cp = require('child_process');
var grunt = cp.spawn('grunt', ['--force', 'default', 'watch'])
grunt.stdout.on('data', function(data) {
// relay output to console
console.log("%s", data)
});
Then just run node app as normal!
Credit

Resources