Node.js child_process has no access to global modules - node.js

I have installed a npm packages globally in my Kubuntu 19.04
$ npm install -g cordova
/home/username/.npm-global/bin/cordova -> /home/username/.npm-global/lib/node_modules/cordova/bin/cordova
+ cordova#9.0.0
updated 1 package in 7.299s
I can access it from shell
$ cordova -v
9.0.0 (cordova-lib#9.0.1)
But I can't access it from a simple node script with spawn:
const { spawn } = require( 'child_process' );
const cmd = spawn( 'cordova', [ '-v' ] );
cmd.stdout.on( 'data', data => {
console.log( `stdout: ${data}` );
} );
Running it results in the following:
$ node test1.js
events.js:298
throw er; // Unhandled 'error' event
^
Error: spawn cordova ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
at onErrorNT (internal/child_process.js:467:16)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Emitted 'error' event on ChildProcess instance at:
at Process.ChildProcess._handle.onexit (internal/child_process.js:273:12)
at onErrorNT (internal/child_process.js:467:16)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
errno: -2,
code: 'ENOENT',
syscall: 'spawn cordova',
path: 'cordova',
spawnargs: [ '-v' ]
}
But when using absolute path:
const { spawn } = require( 'child_process' );
const cmd = spawn( '/home/username/.npm-global/bin/cordova', [ '-v' ] );
cmd.stdout.on( 'data', data => {
console.log( `stdout: ${data}` );
} );
I get the expected result:
$ node test1.js
stdout: 9.0.0 (cordova-lib#9.0.1)
My script above is just a testcase, since I have problem to add/run cordova specific stuff in vue-cli-plugin-cordova and quasar. I tracked it down, that the global path is the problem.
Update
I think I found the problem, but not sure how to solve it. When setting /bin/bash as shell, it works:
cmd = spawn('cordova', ['-v'], {
shell: '/bin/bash'
});
Not sure, why this is needed and why the packages vue-cli-plugin-cordova and quasar don't do it.

Ok, after hours of research and tryouts, I have uninstalled node, installed nvm and latest node, set
nvm use --delete-prefix v13.7.0 --silent >> /dev/null
and added this to ~/.bashrc
and now everything works

how I solve my error, I changed the environment variable PATH: to C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;{plus program paths}
which is
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\nodejs
in my PATH

Related

Unable to get information using https second time(Error: write EPROTO ... final_renegotiate:unsafe legacy renegotiation disabled)

I developed a server which works fine on my system. Then I got a VPS(Virtual Private Server) from my university to deploy the server there too!
To deploy my server on VPS I used docker but I got a strange result when I ran it! I debug the program and find where problem is but I don't know why it occurs and how to fix it.
I use a remote database to get safe primes. First time I get the information without any problem but when server tries to connect to the database for second time, it gets below error:
node:events:498
throw er; // Unhandled 'error' event
^
Error: write EPROTO 80B9B7E0587F0000:error:0A000152:SSL routines:final_renegotiate:unsafe legacy renegotiation disabled:../deps/openssl/openssl/ssl/statem/extensions.c:907:
at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:94:16)
Emitted 'error' event on ClientRequest instance at:
at TLSSocket.socketErrorListener (node:_http_client:442:9)
at TLSSocket.emit (node:events:520:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -71,
code: 'EPROTO',
syscall: 'write'
}
Node.js v17.4.0
npm notice
npm notice New minor version of npm available! 8.3.1 -> 8.5.2
npm notice Changelog: <https://github.com/npm/cli/releases/tag/v8.5.2>
npm notice Run `npm install -g npm#8.5.2` to update!
npm notice
The simplified server I used to test:
const express = require('express');
const debug = require('debug');
const https = require('https')
const log = debug('app::main-Interface');
const args = process.argv.slice(2);
const app = express();
const port = args[0] || process.env.port || 3000;
function sleep(toSleep){
return new Promise((resolve, reject)=>{
setTimeout(() => {
resolve(true)
}, toSleep);
})
}
async function initializeRemotely(lengthOfOrder = 4096){
return new Promise((resolve, reject)=>{
https.get(`https://2ton.com.au/getprimes/random/${lengthOfOrder}`,
(res)=>{
res.on('data', async (data)=>{
log('Data received!')
resolve(true);
})
}
)
})
}
async function DEBUG(){
let breakTime = 5000;
while(true){
await initializeRemotely()
log('First operation succeed')
await sleep(breakTime);
breakTime *= 2;
}
}
app.listen(port, async () => {
log(`Server started listening on port : ${port}`);
//schedulerPool.MSRulesWatcher(config.get('Times.schedulers'));
DEBUG()
});
I run this code on my system using below command line:
$ DEBUG=app::* node server.js
app::main-Interface Server started listening on port : 3000 +0ms
app::main-Interface Data received! +2s
app::main-Interface First operation succeed +4ms
app::main-Interface Data received! +6s
app::main-Interface First operation succeed +1ms
app::main-Interface Data received! +11s
app::main-Interface First operation succeed +2ms
^C
As you can see it works fine!
The docker file I use to deploy the server is as below(./deploy/Dockerfile):
FROM node:alpine
EXPOSE 3000
WORKDIR /interface
COPY package.json .
RUN npm install
COPY . .
And the content of ./docker-compose.yml:
version: "3"
services:
interface:
image: interface
container_name: interface
build:
context: .
dockerfile: ./deploy/Dockerfile
entrypoint: ["npm", "run", "development"]
Then I run the docker image in VPS using below commands:
$ sudo docker-compose build
$ sudo docker-compose up -d
And the log of server is shown below:
$ sudo docker logs [container-name]
> export NODE_ENV=development; export DEBUG=app:*; node server.js
2022-02-25T17:06:37.963Z app::main-Interface Server started listening on port : 3000
2022-02-25T17:06:40.992Z app::main-Interface Data received!
2022-02-25T17:06:40.998Z app::main-Interface First operation succeed
node:events:498
throw er; // Unhandled 'error' event
^
Error: write EPROTO 80B991E6EB7F0000:error:0A000152:SSL routines:final_renegotiate:unsafe legacy renegotiation disabled:../deps/openssl/openssl/ssl/statem/extensions.c:907:
at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:94:16)
Emitted 'error' event on ClientRequest instance at:
at TLSSocket.socketErrorListener (node:_http_client:442:9)
at TLSSocket.emit (node:events:520:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -71,
code: 'EPROTO',
syscall: 'write'
}
Node.js v17.4.0
npm notice
npm notice New minor version of npm available! 8.3.1 -> 8.5.2
npm notice Changelog: <https://github.com/npm/cli/releases/tag/v8.5.2>
npm notice Run `npm install -g npm#8.5.2` to update!
npm notice
Which indicates server can connect to the database first time but second time it gets this error.
MY QUESTIONS:
First of all, I'm really curious to find out why this problem occurs?
How can I fix it?
INFORMATION
VPS information:
$ uname -a
Linux vote 5.4.0-26-generic #30-Ubuntu SMP Mon Apr 20 16:58:30 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
My system information:
$ uname -a
Linux milad-pc 5.4.178-1-MANJARO #1 SMP PREEMPT Tue Feb 8 20:03:41 UTC 2022 x86_64 GNU/Linux

How to get PostgreSQL dump database file using Node JS

I tried to generate postgresql dump file using Node JS. SO, I used secure-backup library to generate pg-dump file encrypted. I add this package in my project and I configured .pem file also. When I execute this file it's throwing some error. but I couldn't understand what type error is throwing and how to fix it I don't know. Any one give some suggestion how to resolve this issue to generate pg dump file using Node JS otherwise different library used to generate pg dump file.
CODE
let secureBackup = require('secure-backup');
let pgHandler = require('secure-backup/lib/handlers/pg')
console.log('hi')
let backup = secureBackup({
pubKeyPath: 'C:/Users/DELL/Desktop/Twilio_Phone/cert.pem', // path to your public key
outputPath: 'C:/Users/DELL/Desktop/DB_Dump', // where to output your encrypted backup
compress: true, // enable compression (gzip)
handler: pgHandler({
user: 'postgres',
password: '*****',
database: '****'
})
})
backup() // can be invoked directly
// or used with a cron-job module like node-schedule
Error
events.js:292
throw er; // Unhandled 'error' event
^
Error: spawn pg_dump ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:269:19)
at onErrorNT (internal/child_process.js:465:16)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
Emitted 'error' event on ChildProcess instance at:
at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
at onErrorNT (internal/child_process.js:465:16)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: -4058,
code: 'ENOENT',
syscall: 'spawn pg_dump',
path: 'pg_dump',
spawnargs: [ '-U', 'postgres', 'HP', 'hummapi' ]
}

Aws lambda binary file EACCES error

I got Error: spawn EACCES error at the following line when I tried to execute this in aws lambda.
var zip = childProcess.spawn('zip', [
'-r',
job.destination.name,
'./'
], {
cwd: temporaryDirectoryPath
});
I have a binary file 'zip'.
Full error trace:
Error: spawn EACCES
at exports._errnoException (util.js:1018:11)
at ChildProcess.spawn (internal/child_process.js:319:11)
at Object.exports.spawn (child_process.js:378:9)
at createCompressedFile (/var/task/index.js:141:32)
at /var/task/node_modules/async/lib/async.js:718:13
at iterate (/var/task/node_modules/async/lib/async.js:262:13)
at /var/task/node_modules/async/lib/async.js:274:29
at /var/task/node_modules/async/lib/async.js:44:16
at /var/task/node_modules/async/lib/async.js:723:17
at /var/task/node_modules/async/lib/async.js:167:37
Finally, it worked for me. So all errors like EACCES, ENOEN... has gone.
child_process.spawnSync('mybinary', [], {
shell: true
})

Getting Error: spawn ./node_modules/.bin/grunt ENOENT when running grunt

I have a project that is started in development by
yarn start
It runs a index.js that starts a grunt process and get this error:
$ yarn start
yarn start v0.23.2
$ node ./development
grunt_arguments [ '--force', '--notify', '--verbose', '--debug', '--stack' ]
=======================================
Open http://localhost:8000 to start developing
events.js:141
throw er; // Unhandled 'error' event
^
Error: spawn ./node_modules/.bin/grunt ENOENT
at exports._errnoException (util.js:907:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:189:32)
at onErrorNT (internal/child_process.js:355:16)
at nextTickCallbackWith2Args (node.js:458:9)
at process._tickCallback (node.js:372:17)
at Function.Module.runMain (module.js:443:11)
at startup (node.js:139:18)
at node.js:990:3
error Command failed with exit code 1.
No idea what can it be. Environment is:
Win10
Running with MINGW64
I usually monkey patch child_process to help me debug that kind of issues. Add something like this in the beginning of your index.js file:
const util = require('util')
const childProcess = require("child_process");
const originalSpawn = childProcess.spawn;
childProcess.spawn = function() {
console.trace('SPAWN');
console.log('ARGS');
console.log(util.inspect(arguments, false, null)); // showHidden = false, depth = null
return originalSpawn.apply(this, arguments);
};
If your run, childProcess.spawn('ls', ['-lh', '/usr']) you will see something like:
Trace: SPAWN
at Object.childProcess.spawn (repl:2:9)
at myFunction (repl:2:14)
at repl:1:1
at REPLServer.defaultEval (repl.js:164:27)
at bound (domain.js:250:14)
at REPLServer.runBound [as eval] (domain.js:263:12)
at REPLServer.<anonymous> (repl.js:392:12)
at emitOne (events.js:82:20)
at REPLServer.emit (events.js:169:7)
at REPLServer.Interface._onLine (readline.js:210:10)
ARGS
{ '0': 'ls', '1': [ '-lh', '/usr' ] }
Maybe after running it you can update your question with the new information.

spawnSync('npm', ['install']) gives [Error: spawnSync npm ENOENT]

I am having an issue with spawnSync is giving me ENOENT with simple "npm install". Can someone please help me?
======= NODE SCRIPT ==========
var child = require('child_process').spawnSync('npm', ['install']);
console.log(child.error);
===== OUTPUT ==========
[Error: spawnSync npm ENOENT]
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawnSync npm',
path: 'npm',
spawnargs: [ 'install' ]
only on windows but not on OS X.
This happens on
windows 7 x64
node version: 4.4.3
npm version: 2.15.1
I figured out the issue. On Windows, some commands need to be suffixed with .cmd in order to work. In this example, this updated command works for me:
require('child_process').spawnSync('npm.cmd', ['install']);
Or you can use cross-spawn to make it work cross-platform
I solved this by specifying the shell to be the v1 32-bit Powershell executable.
I don't know if there is a more reliable method of getting the Powershell executable path, but this is what I did:
const { spawnSync } = require('child_process')
const path = require('path')
const shell = process.platform === 'win32'
? 'C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe'
: undefined
const r0 = spawnSync('pnpm', ['run', 'build'], {
cwd: path.join(__dirname, '..', 'projects', 'project-name'),
env: process.env,
stdio: 'inherit',
shell
})
if (r0.error) {
console.log(r0.error)
process.exit(1)
}

Resources