How to use npm.commands.version to bump the package.json version programatically - node.js

I'd like the package.json version of my project to bump up every time I run my project, for that I installed the npm package into my project as a local node-module but the following does not work:
var npm = require('npm');
npm.load(function (e, n) {
n.commands.version("patch", function (error) {
// 'error' here equals an error message as shown below
console.log(error);
});
});
Error message
"npm version [ | major | minor | patch | prerelease | preminor | premajor ](run in package dir)'npm -v' or 'npm --version' to print npm version (2.4.1)'npm view version' to view a package's published version'npm ls' to inspect current package/dependency versions"
Any idea what's missing and how to make it work?
Thanks!
Btw, I don't use grunt and not planning to at this point, so grunt-bump is not an option.

Well when I read the docs, I see "Like all other commands, this function takes a string array as its first parameter", which means you need ["patch"] where you have "patch":
var npm = require('npm');
npm.load(function (e, n) {
n.commands.version(["patch"], function (error) {
// 'error' here equals an error message as shown below
console.log(error);
});
});
That works fine for me.

Related

Node JS upgrade to 16.18 issue: File and Request types not found

I have upgraded from Node version 14 to node version 16.8.
λ node --version
v16.18.0
What I am seeing is, when I am running nest start --debug --watch, once the build is done successfully, it is keep on complaining the following weird stuffs. Everything was working fine with node-js 16.5.0 earlier.
Just to give you a hint, I upgraded to node js 16.5.0 to 18.x first. But as then it was decided to use node 16.18.0. So I uninstall node js in my laptop and install nodejs 16.18.0.
The errors are something like this:
import { createParamDecorator, ExecutionContext } from '#nestjs/common';
import { Request } from 'express';
export const AuthToken = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
return getAuthToken(request);
},
);
export const getAuthToken = (request: Request): string => {
return request.headers['authorization']?.replace('Bearer ', '');
};
And the error is:
TS2304: Cannot find name 'Request'.
8 | );
9 |
> 10 | export const getAuthToken = (request: Request): string => {
| ^^^^^^^
11 | return request.headers['authorization']?.replace('Bearer ', '');
12 | };
13 |
Similarly another code snippet:
import fs from 'fs';
import { isUndefined } from 'lodash';
import path from 'path';
export class FileUtil {
public saveMediatorLog(parentDir: File, instanceId: string, content: File) {
const srcFilePath: string = `${parentDir}/instance_${instanceId}_mediatorLog.tgz`;
const destFilePath: string = `${parentDir}/${content.name}`;
const srcFileWithAbsolutePath = path.resolve(srcFilePath);
const destFileAbsolutePath = path.resolve(destFilePath);
fs.stat(srcFilePath, function(err) {
if (isUndefined(err)) {
fs.copyFile(srcFileWithAbsolutePath, destFileAbsolutePath, (err) => {
if (err) {
throw err;
}
});
}
});
}
}
When I click on File to see the definition, it leads me to:
It has a name.
But it complains this:
TS2339: Property 'name' does not exist on type 'File'.
6 | public saveMediatorLog(parentDir: File, instanceId: string, content: File) {
7 | const srcFilePath: string = `${parentDir}/instance_${instanceId}_mediatorLog.tgz`;
> 8 | const destFilePath: string = `${parentDir}/${content.name}`;
| ^^^^
Some of my versions are:
Node Js: 16.18.0
"#types/node": "^14.14.31",
"typescript": "^4.1.5"
"ts-node": "^10.9.1",
I am really not able to understand where the issue is or what is the remedy.
For me: the issue was: yarn cache (may be some older versions were there).
So I did a forceful cache clean this:
yarn cache clean --force
rm yarn.lock
This solves the issue.
However there are quite a few dependency mismatches still exists which ideally I will fix over time.
Getting everything clean after upgrading to Node is not an easy task, seems:
Yarn Dependency errors:
warning "#nestjs/swagger > #nestjs/mapped-types#0.4.1" has incorrect peer dependency "class-transformer#^0.2.0 || ^0.3.0 || ^0.4.0".
warning " > #nestjs/typeorm#9.0.1" has incorrect peer dependency "#nestjs/common#^8.0.0 || ^9.0.0".
warning " > #nestjs/typeorm#9.0.1" has incorrect peer dependency "#nestjs/core#^8.0.0 || ^9.0.0".
warning " > #nestjs/typeorm#9.0.1" has incorrect peer dependency "rxjs#^7.2.0".
warning "#ssut/nestjs-sqs > sqs-consumer#5.7.0" has incorrect peer dependency "aws-sdk#^2.1114.0".
warning " > swagger-ui-express#4.4.0" has unmet peer dependency "express#>=4.0.0".
warning " > #nestjs/schematics#8.0.11" has incorrect peer dependency "typescript#^3.4.5 || ^4.3.5".
warning " > ts-loader#8.3.0" has unmet peer dependency "webpack#*".
A better option is to try npm install for such a case. As npm builds the dependency sequentially (yarn does it as parallel as possible), you will get step by step errors. (Of course you can override it using --legacy-peer-deps like this):
npm install --legacy-peer-deps
Without this you will get very nice errors like this:
# npm resolution error report
2022-11-05T13:47:27.128Z
While resolving: gradual-deploy#0.0.1
Found: #nestjs/common#7.6.18
node_modules/#nestjs/common
#nestjs/common#"^7.6.13" from the root project
Could not resolve dependency:
peer #nestjs/common#"^8.0.0 || ^9.0.0" from #nestjs/typeorm#9.0.1
node_modules/#nestjs/typeorm
#nestjs/typeorm#"^9.0.1" from the root project
Fix the upstream dependency conflict, or retry
this command with --force, or --legacy-peer-deps
to accept an incorrect (and potentially broken) dependency resolution.
I tried to manually resolves one by one. But the issue is: at the runtime there were so much dependency mismatches, I lost.
So I clean up the yarn cache and take a shortcut to unblock myself.

How to fix: Error: If .NET source is provided as JavaScript function, function body must be a /* ... */ comment

I am trying to run the basic hello world example from the documentation from here (it's the first example on the page):
https://github.com/agracio/edge-js
I have a typescript file that I am running (see the code below). I am on node version 9.9.0 on a Windows 10 64 bit. I have made only the following installations:
npm install edge
npm install edge.js
npm install #types/node --save-dev
I have made the installations to the same directory as the typescript file.
I am able to run ts-node app.ts in the command line and have it console.log("hi") successfully in that directory.
However, when I change my code to the example below, it is giving me the error throw new Error('If .NET source is provided as JavaScript function, function body must be a /* ... */ comment.');
I had originally tried doing this using edge.js but I kept getting the error that I needed to precompile. For the life of me I couldn't get it to find my python executable when executing build.bat release 10.5.3. (Despite including an environment variable PYTHON with a value of c:\Python\Python37\python.exe) I wanted to try using edge-js because it was already precompiled. I downgraded node to 9.9 (I uninstalled node 10.15.3 and then installed the 9.9.0 msi from the website) because I thought edge-js only supported version 9. Well here I am trying to run edge-js with version 9 and I am still getting an error, although it is a different error.
Here is the code I am trying to run:
var edge = require('edge-js');
var helloWorld = edge.func(function () {/*
async (input) => {
return ".NET Welcomes " + input.ToString();
}
*/});
helloWorld('JavaScript', function (error, result) {
if (error) throw error;
console.log(result);
});
I can't believe this worked. It was a syntax error. A problem with the amount of whitespace between the comment and the end of the function. Here is the correct syntax:
var edge = require('edge-js');
var helloWorld = edge.func(function () {
/*async (input) => {
return ".NET Welcomes " + input.ToString();
}*/
});
helloWorld('JavaScript', function (error, result) {
if (error) throw error;
console.log(result);
});

Get list of all NPM dependencies minimum node.js engine version

We have an NPM project X. I want to get a distinct list of all the dependencies in the project and the minimum Node.js (engine) version that they need.
How can I do this?
The motivation is of course to discovery what the minimum Nodejs version we need to run in development and production.
npm ls | grep "engines"
something like that, except the above won't work, hopefully there is something more robust
I was able to accomplish this like so:
let npm = require('npm');
npm.load({}, function(err, npm) {
if(err) throw err;
npm.config.set('global', false); // => we don't want to consider global deps
npm.commands.list([], true, function(err, pkgInfo) {
let enginesList = Object.keys(pkgInfo.dependencies).map(function(k){
return {
dep: k,
engines: pkgInfo.dependencies[k].engines || {}
}
});
enginesList.forEach(function(val){
console.log(val.dep + ' => ', val.engines);
});
});
});

Prevent NodeJS npm from printing details when retrieving package

Using the node npm module (https://www.npmjs.org/api/npm.html), I want to retrieve a package but NOT have it print the results to console. Setting loglevel silent does not seem to help.
var npm = require('npm');
npm.load(function (er, npm) {
// use the npm object, now that it's loaded.
npm.config.set('loglevel', 'silent');
npm.commands.view(["<package>#<version>"],function(err, npmBody) {
//at this point it is always logging npmBody contents to console!
});
});
This can't be done without hijacking stdout. See: https://github.com/npm/npm/blob/master/lib/install.js#L100
This was fixed once, but then reverted. It appears that npm is not designed to be use programmatically.
By "hijacking stdout" I mean something like this:
console.log('Begin');
console._stdout = { write : function () {} };
externalFn();
console._stdout = process.stdout;
console.log('End');
function externalFn () {
console.log('Annoying stuff');
}

Can I make npm install follow a certain package.json format?

When you install an npm package and use the --save, --save-dev or --save-optional options to write the package into your package.json file in the appropriate dependencies property, the entire file appears to be rewritten with 2-space indentation:
$ cat package.json
{
"name": "my-package"
}
$ npm install --save another-package && cat package.json
{
"name": "my-package",
"dependencies": {
"another-package": "~0.1.5"
}
}
Is there any way to make npm follow the existing format, or to specifiy a custom format (e.g. 4-space indentation) for the package.json file?
I can't find anything in the npm options documentation.
After digging through the npm source, it unfortunately appears the answer to my question is definitely "no". When npm install is executed with one of the "save" options, the following happens:
fs.readFile(saveTarget, function (er, data) {
try {
data = JSON.parse(data.toString("utf8"))
} catch (ex) {
er = ex
}
// ...
data = JSON.stringify(data, null, 2) + "\n"
fs.writeFile(saveTarget, data, function (er) {
cb(er, installed, tree, pretty)
})
})
The important line is the call to JSON.stringify. When invoking stringify with the third argument, the returned string indentation is formatted with the specified number of spaces.
Since there is no way to customise the value used by npm internally, this behaviour is currently non-configurable.
Fixed in 64b67f0 and npm 5...
https://github.com/npm/npm/issues/4718#issuecomment-307142397

Resources