Path is undefined, - node.js

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
What could be the possible reason? I searched a lot, it is giving error for a particular function.
here`s the first line of the function that is being called
path.resolve(__dirname, 'templates');

The error is because __dirname is coming as undefined. __dirname only works for scripts. If you're trying to run it in REPL it won't work and i think you're doing that.
create a new file test.js and copy paste the line below in it
console.log(path.resolve(__dirname, 'templates'));
and run it:
node test.js
Hope this helps

Related

#loadable/server pass the whole stats JSON to eval('require')(modulePath)

I'm trying to setup SSR for react app with #loadable/components. I setup all based on docs with babel and webpack plugins. When I try to run node server.js it runs ok but when I open a browser and throws the following error (into node console):
TypeError [ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received an instance of Object
at validateString (internal/validators.js:118:11)
at Module.require (internal/modules/cjs/loader.js:1033:3)
at require (internal/modules/cjs/helpers.js:72:18)
at smartRequire (/Users/max/Documents/repos/app/node_modules/#loadable/server/lib/util.js:44:25)
at new ChunkExtractor (/Users/max/Documents/repos/app/node_modules/#loadable/server/lib/ChunkExtractor.js:181:50)
at renderer (webpack://app/./node_modules/#MYSCOPE/elm/dist/elm.esm.js?:3619:19)
at eval (webpack://app/./src/server.tsx?:64:90)
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
code: 'ERR_INVALID_ARG_TYPE'
}
As you can see there is #MYSCOPE in the traceback which holds some of my internal packages (if it matters).
#loadable/server/lib/util.js is the following function:
And when I try to console.log(modulePath) on line 42 I see a whole stats JSON output which seems wrong and I should get a single module path (as I understand).
Any help?
I can share some specific parts of my configuration files if needed. Because I see my own package in console output seems like something is wrong with it's build (it works perfectly on the client-side with cjs build), but having full stats object as module path is very confusing.
UPD: Demo https://www.dropbox.com/s/9r947cgg4qvqbu4/loadable-test.zip?dl=0
Run
yarn
yarn dev:server
# go to localhost:3000 and see the error in console
to rebuild:
yarn
yarn dev:build-client
yarn dev:build-server
yarn dev:server # go to localhost:3000
The statsFile option passed to ChunkExtractor expects a path to the loadable-stats.json file, not the actual JSON content of it. By doing require('../loadable-stats.json'), webpack actually resolve the JSON during build time and assign it to the loadableJson variable.
You can change your loadableJson as follow:
import path from 'path';
const loadableJson = path.resolve(__dirname, '../bundle_client/loadable-stats.json');
This will solve the problem you had on your question. But, if you only do this, you will notice that you have another problem. Loadable by default assumes that your entry chunk name is main. This is not the case in your demo, as you have set the entry chunk name to be app instead.
entry: {
app: ['#babel/polyfill', './src/index.tsx']
},
To solve this, simply tell loadable about your entrypoints names by passing an array to the ChunkExtractor contructor as such:
const extractor = new ChunkExtractor({
statsFile: loadableJson,
entrypoints: ["app"], // name of your entry chunk
});
That's it, everything should now be working properly!
If it helps, I set up the demo on GitHub so you can easily see the changes I made here.

"dotenv: error when sourcing '.env' file"?

Every time I cd a particular directory using either Terminal or iTerm2 (I'm running Macos 10.14.5, Node 12.13.0), I get the following error that seems to be complaining about an ´.env´ file provided to me by my team. They are not getting the error.
.env:22: parse error near '}'
dotenv: error when sourcing '.env' file
.env:22: parse error near '}'
Line 22, which seems to be causing the error is
COOKIE_SETTINGS={"isSecure": false, "isSameSite": false, "isHttpOnly": true, "encoding": "base64json", "path": "/"}
Any clue how I might remedy this? Thanks for any insights.
You can't store objects inside .env file.
The solution is to:
Stringify JSON object and save as env variable. Then parse and use it when you need your object.
Another solution is to write variables like this:
COOKIE_SETTINGS_IS_SECURE = false
COOKIE_SETTINGS_IS_SAME_SITE = false
...
This seem error when parsing env.
I think env just support like string or number for this case.
Maybe you can use in .env
COOKIE_SETTINGS="{'isSecure': false, 'isSameSite': false, 'isHttpOnly': true, 'encoding': 'base64json', 'path': '/'}"
In JS just use JSON.parse to turn back to Object
cookieSettings= process.env.DB_HOST ? JSON.parse(process.env.DB_HOST) : null;

nodejs __dirname is a dot when I try to execute a script directly in package.json file

Here is a chunk of my package.json file:
{
...
"scripts": {
"run-test": "node -e 'require(`my-test-lib`).whichPath(__dirname )'",
},
...
}
When I read my function param into the 'test' script, it is a simple dot . :-s
I thought that __dirname was always absolute, but it's not the case...
I've used process.cwd() for the moment, but I'm curious why this is not working. Have you got a clue ?
While I was searching, I found this question that is related to the subject and I found relevant, but it has no answer.
__dirname
has a different value depending on which file is invoked it in, whereas.
#laggingreflex mentioned in comments: "The docs describe __dirname to be "The directory name of the current module". Since you're using -e flag to execute the code, no module is actually loaded, so it'd make sense not to expect an actual path from it"
process.cwd()
always returns the same value, which is the absolute path of where you started the Node.js process (eg., $ node index.js).
console.log(__dirname); // /project
console.log(process.cwd()); // /project
const test = require('./module');
/* module code
console.log(__dirname); /project/module
console.log(process.cwd()); /project
*/

How to pass command line argument in electron

I just started using electron. I have a doubt about how to pass command line arguments in electron when I'm using npm start to run electron.
In Node.js I am using: node server.js one two=three four
command prompt for :
var arguments = process.argv.slice(2);
arguments.forEach(function(val,index, array) {
console.log(index + ': ' + val);
});
In Node.js is working. I need to know how can I make this work in electron.
Can someone please give a solution for this?
The way of passing arguments will be same, the only thing you have to take care is path of electron. In package.json its written npm start will perform electron main.js. So you will have to execute this command explicitly and pass arguments with "proper path of electron" i.e ./node_modules/.bin/electron. Then the command will be
./node_modules/.bin/electron main.js argv1 argv2
and these arguments you can access by process.argv in main.js
and If wish you to access these parameters in your app then there are following things to do :
1.In your main.js define a variable like
global.sharedObject = {prop1: process.argv};
2.In your app just include remote and use this sharedObject
const remote = require('electron').remote;
const arguments = remote.getGlobal('sharedObject').prop1;
console.log(arguments);
3.Output will be ["argv1", "argv2"]

mocha fs.existsSync always failing

I am attempting to check if a file exists in my mocha test. I know for a fact that the file exists in the test folder(I am placing it there for simplicity while I try and get this to work). But no matter what I do, fs.existsSync always fails. Logger.startup() creates the file. Logger.getFilename() returns a value like 5-17-30-2013.log. I am new to mocha so have no clue if I am making a classic blunder. As far as I know I am using mocha synchronously. Thanks for all of the help.
Here is my Mocha Test script:
var logger = require('../logger');
var fs = require('fs');
describe("Logger", function () {
it("Creates a file", function () {
logger.startup();
console.log(logger.getFilename());
if (!fs.existsSync(logger.getFilename())) {
throw ("Logging File Does Not Exist");
}
})
})
The currently accepted self-answer's explanation falls short. It says:
Apearently fs looks at the root of the project, the package.json folder, and not realative to the file calling it, which I did not know.
Sure, but it's not happenstance or a quirk of the fs module. The fs module uses process.cwd() to interpret relative paths passed to it. Unless it is changed with process.chdir(), process.cwd() is the directory in which the current process has been started. Since mocha is usually launched from the root of a project, then in a mocha process, process.cwd() is usually going to be the root of the project. If mocha were launched from a different directory, then process.cwd() would have a different value.
The confusion may come from how the module system handles relative paths. A module name with a relative path will be interpreted relative to the __dirname of the current file. This may be a value different from process.cwd().
try using process.cwd() to determine the working directory fs.exists is running from
I believe you are looking for __dirname, try to prepend it to the filename.
Documentation: http://nodejs.org/api/globals.html#globals_dirname
I followed #jjm and his advice on the program. After logging where it thought the file was, it turns out that it was looking in the folder "logger", not "logger/test" Apearently fs looks at the root of the project, the package.json folder, and not realative to the file calling it, which I did not know.
You can use fs.open(filepath, 'r', callback);
http://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback
This worked for me:
describe("Logger", function () {
it("Creates a file", function (done) {
logger.startup();
console.log(logger.getFilename());
fs.readFile(logger.getFilename(), done);
});
});

Resources