How to Change Default Directory in Node.JS - javascript

I am trying to change the default folder in node.js. I went to the following link in the node.js documentation:
https://nodejs.org/api/process.html#process_process_chdir_directory
I then generated the following code in a .js file:
console.log('Starting directory: ${process.cwd()}');
try {
process.chdir('C:\Users\HalvorSD\node-party');
console.log('New directory: ${process.cwd()}');
} catch (err) {
console.error('chdir: ${err}');
}
I get the error thrown in my console. The directory does exist so that's not the problem. Is my directory formatting incorrect or what's my issue?
I am trying to change the default from C:/Windows/System32/ to what I have above. Any help would be much appreciated.

JavaScript uses \ for String escape sequences. Use \\ for a literal backslash:
process.chdir('C:\\Users\\HalvorSD\\node-party');
Alternatively use path.join for cross-platform paths:
const path = require('path')
process.chdir(path.join('C', 'Users', 'HalvorSD', 'node-party'));

If you are going to change default directory for "Node.js command prompt" every time, when you launch it, then (Windows case)
go the directory where NodeJS was installed
find file nodevars.bat
open it with editor as administrator
change the default path in the row which looks like
if "%CD%\"=="%~dp0" cd /d "%HOMEDRIVE%%HOMEPATH%"
with your path. It could be for example
if "%CD%\"=="%~dp0" cd /d "c://MyDirectory/"
if you mean to change directory once when you launched "Node.js command prompt", then execute the following command in the Node.js command prompt:
cd c:/MyDirectory/

Related

use vscode command in terminal No such file or directory

when I use code command, I get the error
$ code 2to3
/usr/local/bin/code: line 10: Loading sentinel dylib...
Successfuly loaded sentinel.dylib.
/Applications/Visual Studio Code.app/Contents/MacOS/Electron: No such file or directory
Just add the VSCode bin path to the path environment variable.
The path showing in my Windows system is C:\Users\sas\AppData\Local\Programs\Microsoft VS Code\bin
For Mac follow this Run / Open VSCode from Mac Terminal

How can I use ffplay from Electron.js app?

I've installed ffplay in my working folder (in bin subfolder) using ffbinaries (ffbinaries downloader). My current platform is linux-64.
I've use:
var spawn = require('child_process').spawn,
player = spawn('./bin/ffplay', ['http://path_to_video_file']);
but got an error in terminal stderr:
./bin/ffplay: error while loading shared libraries: libSDL2-2.0.so.0: cannot open shared object file: No such file or directory child process exited with code : 127
How can I get access from my javascript code to this binary for playing videos or how can I get ready-to-use binary which is a built-in for my Electron app?
...Or how can I get all of ffplay possibilities for playing videos inside Electron app?
Thanks in advance!
The error you get means that ffplay cannot find libSDL.
First, make sure the library is installed by opening a terminal window and typing:
sudo apt install libsdl2-dev
If it wasn't installed, try to run your program again after it was installed.
If you still have the problem, type the following in your terminal window:
export LD_LIBRARY_PATH="/usr/local/lib"
Try again to run your program. If the problem is now solved, edit the file etc/environment and add the setting there to make it permanent:
sudo nano /etc/environment
Add this LD_LIBRARY_PATH="/usr/local/lib" at the end, exit and save.
Hope it helps.

Pathing issues with using ./ in a Rakefile on Windows

I have the following Rakefile...
namespace :dev do
desc "Execute my-bash-script."
task :done do
sh "./bin/my-bash-script.sh" # <-- Error on this line
end
end
Which I execute successfully on my Mac with rake dev:done
When I run the command on my Windows machine however, I receive a Command failed with status (127) error on the sh "./bin/my-bash-script.sh" line.
I figured there was a pathing issue with using ./ so I tried replacing ./ in the Rakefile with #{File.dirname(__FILE__)} but am still receiving the same error.
What am I doing incorrectly?
Under windows, passing forward slashes in a path to the shell does not work.
You need to replace all '/' with '\' in the command string.

Cannot run nodejs script in command prompt

When I try to run a node.js program in Windows command prompt by stating its location, it will invariably say:
[stated location] is not recognized as an internal or external command, operable program or batch file.
In all answers to similar questions, in all node.js manuals, it is assumed you can just run a node.js file by calling it from its location. There will always be the suggestion of trying some hello world example BEFORE establishing a server and so on.
Even if I clean the command prompt with prompt $ cmd, and then write the whole location manually, I get the same message.
When I run
echo %path%
I get C:\Program Files\nodejs\bin
When I run
node -v
I get v6.10.3
When I run
node a00.js
(where a00.js is the script's name), it believes the whole path is a module, so it says it cannot recognize that module.
If I clear the command prompt with prompt $ cmd and then run node a00.js, it believes a00.js to be a module, so it says it cannot recognize that module.
Your path knows where node.js is, but it does not know where a00.js is. So you need to run the command as node followed by the path to file. (copy all commands including the double quotes)
node "C:\Program Files\nodejs\a00.js"
As an example, try this.
create a file called hello.js save it in C:\Windows\Temp\ (or where you prefer)
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
now open cmd and run it like this (assuming you saved it in C:\Windows\Temp\
node "c:\Windows\Temp\hello.js"
if you run it from path, meaning you CD to the directory where the a00.js file exists, then only can you run it as `node a00.js
as an example, assuming a00.js exists in C:\Windows\Temp:
cd c:\Windows\Temp
node a00.js
Important note when using any path, always enclose it in double quotes.
This will cause errors:
node C:\Program Files\test\a00.js
This will work:
node "C:\Program Files\test\a00.js"
I had a similar problem when node.js was complaining module does not exist , that is because it lets you save with a file name for eg If statement.js however when you call it in commander it does not like it so try changing the file name and run it and that could fix similar issues

How to access chromedriver logs for Protractor test

I have seen that chromedriver can output a logfile (https://sites.google.com/a/chromium.org/chromedriver/logging)
This page shows how to set this up when executing the exe directly:
chromedriver.exe --verbose --log-path=chromedriver.log
I cannot figure out how to set this up in Protractor however
My current protractor.conf.js
require('babel/register');
exports.config = {
framework: 'jasmine2',
seleniumServerJar: './node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar'
};
From #alecxe's answer below and protractor's browser setup docs I tried adding the following (with and without --s) but with no apparent effect:
capabilities: {
browserName: "chrome",
chromeOptions: {
args: [
"--verbose",
"--log-path=chromedriver.log"
]
}
}
I also tried specifying an absolute path (log-path=/chromedriver.log) which also didn't work.
You can always start up your own instance of chromedriver in a separate process and tell Protractor to connect to that. For example, if you start chromedriver with:
chromedriver --port=9515 --verbose --log-path=chromedriver.log
Then you could use a configuration file for Protractor like so:
exports.config = {
seleniumAddress: 'http://localhost:9515',
capabilities: {
'browserName': 'chrome'
},
specs: ['example_spec.js'],
};
We use a shell script to add chromedriver logging, among other checks. You can then point protractor at the shell script:
protractor config:
// When running chromedriver, use this script:
chromeDriver: path.resolve(topdir, 'bin/protractor-chromedriver.sh'),
bin/protractor-chromedriver.sh
TMPDIR="/tmp"
NODE_MODULES="$(dirname $0)/../node_modules"
CHROMEDRIVER="${NODE_MODULES}/protractor/selenium/chromedriver"
LOG="${TMPDIR}/chromedriver.$$.log"
fatal() {
# Dump to stderr because that seems reasonable
echo >&2 "$0: ERROR: $*"
# Dump to a logfile because webdriver redirects stderr to /dev/null (?!)
echo >"${LOG}" "$0: ERROR: $*"
exit 11
}
[ ! -x "$CHROMEDRIVER" ] && fatal "Cannot find chromedriver: $CHROMEDRIVER"
exec "${CHROMEDRIVER}" --verbose --log-path="${LOG}" "$#"
According to the protractor's source code, chromedriver service is started without any arguments and there is no direct way to configure the arguments. Even though the chromedriver's Service Builder that protractor uses actually has an ability to specify the verbosity and the log path:
var service = new chrome.ServiceBuilder()
.loggingTo('/my/log/file.txt')
.enableVerboseLogging()
.build();
Old (incorrect) answer:
You need to set the chrome arguments:
capabilities: {
browserName: "chrome",
chromeOptions: {
args: [
"verbose",
"log-path=chromedriver.log"
]
}
},
See also:
Viewing outstanding requests
Since, the previous answer by #P.T. didn't work for me on Windows 7, I started with his suggestions and got it working on Windows. Here is a working solution for Windows 7 users.
STEP 1: Install BASH and JQ and confirm they are working on your Windows box
Download bash (for Windows 10
https://itsfoss.com/install-bash-on-windows/ ; for Windows 7
download latest here:
https://sourceforge.net/projects/win-bash/files/shell-complete/latest/ ; for Windows Server 2012 or any Windows OS that already has Git installed on it, you already have a bash.exe and sh.exe installed at C:\Program Files\Git\usr\bin or C:\Program Files (x86)\Git\usr\bin already
)
Install bash - For Windows 7/ download it and extract the zip files to a directory.
Download jq (https://stedolan.github.io/jq/) and install it in the same directory location as bash
Make SURE that you add your above directory (for Windows 7- where you extracted the bash zip files to; for other applicable OSes that have git, the path it is installed at) to your PATH system environment variable.
Once the above is installed and added to your PATH, close ALL and reopen Webstorm and any CMD windows you wish to run your work in.
Test that bash is actually installed by simply typing it on a windows command prompt
C:\git\> bash .
Doing so should produce a bash cmd prompt like this
bash$
STEP 2: Add Custom Files for Redirecting Chromedriver to user Debug Logging
Add the following files to the top level of the project (wherever your protractor-conf.js is located). These files allow us to add custom debug switches to the chromedriver.exe execution.
Note that this is necessary because these switches are not exposed through protractor and cannot be done directly in the protractor.conf.js file via the chromeOptions/args flags as you would normally expect
chromedriver.cmd -- exact source shown below:
bash protractor-chromedriver.sh %*
protractor-chromedriver.sh -- exact source shown below:
TMPDIR="$(dirname $0)/tmp"
NODE_MODULES="$(dirname $0)/node_modules"
SELENIUM="${NODE_MODULES}/protractor/node_modules/webdriver-manager/selenium"
UPDATECONFIG="${SELENIUM}/update-config.json"
EXEFILENAME="$(cat ${UPDATECONFIG} | jq .chrome.last | tr -d '""')"
CHROMEDRIVER="${SELENIUM}/${EXEFILENAME##*'\\'}"
LOG="${TMPDIR}/chromedriver.$$.log"
fatal() {
# Dump to stderr because that seems reasonable
echo >&2 "$0: ERROR: $*"
# Dump to a logfile because webdriver redirects stderr to /dev/null (?!)
echo >"${LOG}" "$0: ERROR: $*"
exit 11
}
[ ! -x "$CHROMEDRIVER" ] && fatal "Cannot find chromedriver: $CHROMEDRIVER"
exec "${CHROMEDRIVER}" --verbose --log-path="${LOG}" "$#"
/tmp -- create this directory at the top level of your project (same as the location of the protractor.conf.js file.
STEP 3: Update protractor.conf.js file.
In the protractor.conf.js file, add the following line as a property in the exports.config object. As in:
exports.config = {
.. ..
chromeDriver: 'chromedriver.cmd',
.. ..
STEP 4: Launch your tests
your test should now run and if the chrome driver outputs any log information it will appear in a file called chromedriver.???.log in the tmp directory under your project.
Important caveats
This script set up assumes you install and run protractor (and the chrome driver under it) within the local node_modules directory inside your project. That is how I run my code, because I want it complete self-contained and re-generated in the build process/cycle. If you have protractor/chromedriver installed globally you should change the CHROMEDRIVER variable within the protractor-chromedriver.sh file to match your installation of protractor/chrome driver.
hope that helps.
If you're using the seleniumServerJar, in protractor.conf.js set the logfile path to wherever you want it to write the file:
seleniumArgs: [
'-Dwebdriver.chrome.logfile=/home/myUsername/tmp/chromedriver.log',
]
If you're using webdriver-manager start to run a local selenium server, you'll need to edit the webdriver-manager file:
// insert this line
args.push('-Dwebdriver.chrome.logfile=/home/myUsername/tmp/chromedriver.log');
// this line already exists in webdriver-manager, add the push to args before this line
var seleniumProcess = spawnCommand('java', args);
In case you use webdriver-manager: webdriver manager has the chrome_logs option (you can find it in its source code (in opts.ts or opts.js in the compiled code)), so you can use it something like:
webdriver-manager start --chrome_logs /path/to/logfile.txt
I'm using this as a global afterEach hook (mocha):
afterEach(() => {
browser.manage().logs().get('browser').then(function(browserLog) {
if(browserLog && browserLog.length) {
console.log('\nlog: ' + util.inspect(browserLog) + '\n');
}
});
});

Categories