spawn ls ENOENT when watched file is modified - javascript

I am learning Node.js via the book Node.js the Right Way. I am trying to run the following example to watch changes to a file called target.txt that resides in the the same directory as the .js file.
"use strict";
const
fs = require('fs'),
spawn = require('child_process').spawn,
filename = process.argv[2];
if (!filename) {
throw Error("A file to watch must be specified!");
}
fs.watch(filename, function () {
let ls = spawn('ls', ['-lh', filename]);
ls.stdout.pipe(process.stdout);
});
console.log("Now watching " + filename + " for changes...");
I get the following error when I change the text file and save it:
events.js:160
throw er; // Unhandled 'error' event
^
Error: spawn ls ENOENT
at exports._errnoException (util.js:1018:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
at onErrorNT (internal/child_process.js:367:16)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
Node.js version: v6.11.0
IDE: Visual Studio Code 1.13.1
OS: Windows 10 64x

There's no ls on Windows, you should use dir instead.
However, that's not an executable. To run .bat and .cmd files you can:
Spawn cmd.exe and pass those files as arguments:
require('child_process').spawn('cmd', ['/c', 'dir']);
Use spawn with the shell option set to true:
require('child_process').spawn('dir', [], { shell: true });
Use exec instead of spawn:
require('child_process').exec('dir', (err, stdout, stderr) => { ... });
For more on that, take a look at this section in the official docs.
EDIT:
I'm not sure I understood you question in the comment correctly, but if you go for the second option, for example, you code will look like this:
...
fs.watch(filename, function () {
let dir = spawn('dir', [filename], { shell: true });
dir.stdout.pipe(process.stdout);
});
...
Please, keep in mind you may need to adjust this code slightly. I'm writing all this from memory as I don't have access to a Windows machine right now, so I can't test it myself.

Related

how to run puppeteer application in replit?

i want to run whatsapp-web.js module in replit using node.js
I tried the program in the library documentation. namely as follows
const qrcode = require('qrcode-terminal');
const { Client, LocalAuth } = require('whatsapp-web.js');
const client = new Client({
authStrategy: new LocalAuth()
});
client.on('qr', qr => {
qrcode.generate(qr, { small: true });
});
client.on('ready', () => {
console.log('Client is ready!');
});
client.on('message', async msg => {
const text = msg.body.toLowerCase() || '';
//check status
if (text === '!ping') {
msg.reply('pong');
}
});
client.initialize();
but when run. i get an error like this
/home/runner/coba-puppeteer/node_modules/whatsapp-web.js/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:241
reject(new Error([
^
Error: Failed to launch the browser process!
/home/runner/coba-puppeteer/node_modules/whatsapp-web.js/node_modules/puppeteer/.local-chromium/linux-982053/chrome-linux/chrome: error while loading shared libraries: libgobject-2.0.so.0: cannot open shared object file: No such file or directory
TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md
at onClose (/home/runner/coba-puppeteer/node_modules/whatsapp-web.js/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:241:20)
at Interface.<anonymous> (/home/runner/coba-puppeteer/node_modules/whatsapp-web.js/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:231:68)
at Interface.emit (node:events:525:35)
at Interface.emit (node:domain:489:12)
at Interface.close (node:readline:590:8)
at Socket.onend (node:readline:280:10)
at Socket.emit (node:events:525:35)
at Socket.emit (node:domain:489:12)
at endReadableNT (node:internal/streams/readable:1358:12)
repl process died unexpectedly: exit status 1
I've found the problem I may be having is that it doesn't have the libraries required by puppeteer on the system. For example, the error message says "libgobject-2.0.so.0" could not be found. It may be a library that puppeteer needs to run. try installing the required libraries by running the following command in your terminal: sudo apt-get install libgobject-2.0-0
however replit cannot use sudo command
with error sudo: The "no new privileges" flag is set, which prevents sudo from running as root.
has anyone ever managed to run a program using whatsapp-web.js in replit?
i am very confused what should i do
the expected output is that it will print the qrcode from whatsapp on the terminal

child_process.exec tries to launch node (instead of shell command) in some odd circumstances

I am trying to run some simple commands using child_process.exec. But in some odd corner cases, it tries to execute the given command with node, rather than the given (or default) shell.
Results
E.g., given below code, I get the following results:
cmd
Result
❌
'"yarn" -v'
Cannot find module 'C:\cwd\yarn.js'
❌
'"npm" -v'
Cannot find module 'C:\cwd\node_modules\npm\bin\npm-cli.js'
✅
'yarn -v'
(works as expected)
✅
'"C:\path\to\yarn" -v'
(works as expected)
OS: Win10
Node: v16., v17. (tried several of them)
EDIT: This seems to be a cmd-specific problem. If I set processOptions.shell = 'bash', it does not occur.
Full Error Message
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module 'C:\cwd\yarn.js'
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
Done - code 1 signal null
Thoughts
It appears that there is a special logic that is triggered, iff the "executable" is in double quotes, and has no spaces or path separators in them...?
Not sure if feature or bug?
Code
// test.js
const cp = require('child_process');
const cmd = '"yarn" install';
const child = cp.exec(cmd);
// ###########################################################################
// process monitoring
// ###########################################################################
child.on('exit', (code, signal) => {
console.log('Done - code', code, ' signal', signal);
});
child.on('error', (err) => {
console.error(`Error:`, err);
});
// inherit stdio
child.stdout.pipe(process.stdout);
process.stdin.pipe(child.stdin);
child.stderr.pipe(process.stderr);
Turns out, it is a volta bug. I filed it here.
Easy to verify: Change the command to do other things on top of "yarn" install. The following still shows hi, but the yarn part still bugs out, so it is definitely not an issue with node or cmd:
const cmd = 'echo "hi" && "yarn" install';
const child = cp.exec(cmd);
Some more explanation: volta manages node, npm and yarn for you, making it very easy to install/uninstall/pin versions globally or even per folder/project. That means that "yarn" install does not actually run yarn, but actually this:
Runs a volta executable
Which will then run yarn...
...which evidently messed up the logic to look up the actual executable.
This happens only with yarn and npm. Everything else (thus far) seems fine, including node itself.

NodeJS can not go to the folder up to execute the command from child_process.spawn

To start WebPack (which is in the parent folder) I use Gulp, but as soon as I try to go to the parent folder in the path, I get an error.
Gulp
var spawn = require('child_process').spawn;
gulp.task('_Scada2', function (done) {
spawn('webpack', [], { cwd: '../../Scada.Web/' })
.on('close', done);
});
get an error
[14:20:47] '_Scada2' errored after 4.47 ms
[14:20:47] Error: spawn webpack ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:229:19)
at onErrorNT (internal/child_process.js:406:16)
at process._tickCallback (internal/process/next_tick.js:63:19)
Процесс завершен с кодом 1.
Try __dirname + '../../Scada.Web/'

Error: spawn node ENOENT

I'm working on my Electron app with Express server and when I build it with electron-packager, I get an error.
Uncaught Exception:
Error: spawn node ENOENT
at exports._errnoException (util.js:1024:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:192:19)
at onErrorNT (internal/child_process.js:374:16)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
at Function.Module.runMain (module.js:607:11)
at startup (bootstrap_node.js:167:16)
at bootstrap_node.js:589:3
here is my main.js where child process is called
const cp = require('child_process');
let instance = cp.spawn('node',['./app.js']);
var electron = require('electron');
var browserWindow = electron.BrowserWindow;
var app = electron.app;
app.on('ready', function(){
// appWindow
var appWindow;
appWindow = new browserWindow({
width:1120,
height:620,
webPreferences: {
plugins: true
},
icon: __dirname + '/public/icon/icon.png'
});
appWindow.loadURL('file://' +__dirname + '/public/prva.html');
//appWindow.webContents.openDevTools();
});
// close app after all windows are closed
app.on('window-all-closed', () => {
app.quit()
})
Does anyone know solution for this error?
You most likely have a problem with your app.js script. You should hook onto some of the event listeners to understand what's really going on. There's an error, exit, close, disconnect, and message events you can listen for. You can also hook onto a number of other things such as the stdin, stdout, stderr as well. Checkout the documentation for the different events, hook onto all of them and output some information and you should be able to track down the issue.
You should also check to see if your express services runs properly directly from the command line rather than from within this Electron app. If it does then you've likely got a path wrong. This could be either that child_process cannot find the "node" application to run, or it can't find your startup script. In either case, you can use the path module to build up the correct path.

Node js Error: spawn node ENOENT with grunt

I'm trying to run a simple grunt task with protractor but everytime I receive an error on the console. I am using grunt with forever utility and placed various breakpoints take narrow down the error causing code. The selenium server created a session for the test cases but the system generates the following error while trying to execute the test suite.
Error: spawn node ENOENT
at exports._errnoException (util.js:746:11)
at Process.ChildProcess._handle.onexit (child_process.js:1046:32)
at child_process.js:1137:20
at process._tickCallback (node.js:355:11)
[launcher] Process exited with error code 1
I cleared all the node processes and still the problem persisted. Any ideas?
Gruntfile.js
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
protractor: {
all: {
options: {
configFile: "conf.js",
keepAlive: true
}
}
}
});
grunt.loadNpmTasks('grunt-protractor-runner');
grunt.registerTask('test', protractor);
};
my_spec.js
this.foreverMonitor = function(port){
forever.list(false, function(){
var child = new (forever.Monitor)('app.js', {
killTree: true,
silent: true
...
});
child.start();
forever.startServer(child);
});
}
var port = 5000;
foreverMonitor(port);
browser.getSession().then(function(sess){
console.log(sess.id);
});
describe('..', function(){
it('..', expect());
});

Categories