Accessing file with relative path (previous folders) in node.js - javascript

I have a folder which holds the JSON file of my Firebase db's, I have a .bat file in Windows which uploads the db's at once. Now I want to duplicate it to MAC.
This is the folder hierarchy:
package-lock.json
node_modules (Folder)
GAME_NAME (Folder)
config.js
serviceAccount.json
Dev (Folder)
import_data.js
upload.sh -> This file i'm running
data (Folder)
Data-worldwide.json
When running upload.sh:
#! /bin/bash
node import_data.js
import_data.js:
// Imports
const firestoreService = require('..\..\node_modules\firestore-export-import');
const firebaseConfig = require('..\config.js');
const serviceAccount = require('..\serviceAccount.json');
// JSON To Firestore
const jsonToFirestore = async () => {
try {
console.log('Initialzing Firebase');
await firestoreService.initializeApp(serviceAccount, firebaseConfig.databaseURL);
console.log('Firebase Initialized');
await firestoreService.restore('./data/Data-worldwide.json');
console.log('Upload Success');
}
catch (error) {
console.log(error);
}
};
jsonToFirestore();
I'm keep getting this error:
xxxxxx#164 Dev % ./upload.sh
internal/modules/cjs/loader.js:651
throw err;
^
Error: Cannot find module '....
ode_modules
irestore-export-import'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:649:15)
at Function.Module._load (internal/modules/cjs/loader.js:575:25)
at Module.require (internal/modules/cjs/loader.js:705:19)
at require (internal/modules/cjs/helpers.js:14:16)
at Object.<anonymous> (/Users/xxxx/Dropbox/JSON Databases/GAME_NAME/Dev/import_data.js:2:26)
at Module._compile (internal/modules/cjs/loader.js:799:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:810:10)
at Module.load (internal/modules/cjs/loader.js:666:32)
at tryModuleLoad (internal/modules/cjs/loader.js:606:12)
at Function.Module._load (internal/modules/cjs/loader.js:598:3)
internal/modules/cjs/loader.js:651
throw err;
^
Error: Cannot find module '....
ode_modules
irestore-export-import'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:649:15)
at Function.Module._load (internal/modules/cjs/loader.js:575:25)
at Module.require (internal/modules/cjs/loader.js:705:19)
at require (internal/modules/cjs/helpers.js:14:16)
at Object.<anonymous> (/Users/xxxx/Dropbox/JSON Databases/GAME_NAME/Dev/import_data.js:2:26)
at Module._compile (internal/modules/cjs/loader.js:799:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:810:10)
at Module.load (internal/modules/cjs/loader.js:666:32)
at tryModuleLoad (internal/modules/cjs/loader.js:606:12)
at Function.Module._load (internal/modules/cjs/loader.js:598:3)

In JavaScript string literals a \ is an escape character.
To have a literal \ in a string you need to escape it: \\ … but Node.js generally uses UNIX-style directory separators (/) and not Windows ones anyway.

Related

Can't find module inside of my folder (discord.js)

As said in the title, I am using discord.js.
Shown below is the error I receive from my console when I try to run npm run start.
node:internal/modules/cjs/loader:922
throw err;
^
Error: Cannot find module './src/commands/clear.js'
Require stack:
- C:\Users\nicod\OneDrive\Desktop\CloudHostedBotCSCS\src\Bot.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:15)
at Function.Module._load (node:internal/modules/cjs/loader:763:27)
at Module.require (node:internal/modules/cjs/loader:991:19)
at require (node:internal/modules/cjs/helpers:92:18)
at Object.<anonymous> (C:\Users\nicod\OneDrive\Desktop\CloudHostedBotCSCS\src\Bot.js:7:15)
at Module._compile (node:internal/modules/cjs/loader:1102:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
at Module.load (node:internal/modules/cjs/loader:967:32)
at Function.Module._load (node:internal/modules/cjs/loader:807:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\nicod\\OneDrive\\Desktop\\CloudHostedBotCSCS\\src\\Bot.js'
]
}
A screenshot of the console will look like this:
Screenshot of console error
Here is the block of code with the problem:
const clear = require("./src/commands/clear.js");
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync("./src/commands/").filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./src/commands/${file}`);
client.commands.set(command.name, command);
}
The part with the problem is const commandFiles = fs.readdirSync('./src/commands/').filter(file => file.endsWith('.js'));. It keeps saying that the module for ./src/commands/ can't be found.
Here is a screenshot of my files: Screenshot of files + folders
No matter how much I tweak my code I still receive this error any ideas why?
Your error is in Bot.js file . that is in src directory.
then import should be require('./commands/clear.js') rather then require('./src/commands/clear.js').
Check directory tree.
instead of using fs.readdirSync('./src/commands/')
#Dario suggested using fs.readdirSync(__dirname+"/src/commands/"), but that still did not work. So I tweaked the code and fs.readdirSync(__dirname+"/commands/") ended up being the solution.

Module not found unless I use a complete path when creating plugins in Hapi

I'm trying to familiarise myself with HapiJS and have been playing around with it this week, I've run into a problem with plugins and paths. I get an error regarding the path I specify when I require a file. I can't use " ./ " without getting an error. The only way to overcome the error is to use the full complete path.
Here's my code that works:
'use strict';
const indexController = require('/Users/mylaptop/docker-node/controllers/IndexController.js');
module.exports.plugin = {
name: 'myPlugin',
version: '1.0.0',
register: async function (server, options) {
// Create a route for example
server.route({
method:'GET',
path:'/test',
handler: function (request, h) {
return indexController.loadIndex(h);
}
});
}
};
However, if I try to require my IndexController file this way:
const indexController = require('./controllers/IndexController.js');
Then I get this error:
internal/modules/cjs/loader.js:583
throw err;
^
Error: Cannot find module '/Users/mylaptop/docker-node/Users/mylaptop/docker-node/controllers/IndexController.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (/Users/mylaptop/docker-node/config/routes/index.js:5:25)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
It doesn't work inside of my plugin, yet outside of my plugin, requiring files this way works fine.
What could be the problem? How can I solve it?
Thanks in advance.
Problem solved with:
const indexController = require('../../controllers/IndexController.js');
My project root folder was 2 directories away, hence ../../ working for me.

Unexpected token ILLEGAL while running node.js mocha test

I have searched all over but have not figured out what I am doing wrong. I am trying to set up mocha for testing node.js javascript application files. I have node installed and have successfully ran basic things on it to confirm it is working.
I installed mocha in my project file, and also have a Makefile and a file called "test" within my project file as well.
Here is the error my terminal(osx 10) is spitting out when I run the command "make test".
humbleMousesMBP:chapter02 humbleMouse$ make test
/Users/humbleMouse/chapter02/test/exchange.test.js:22

^
SyntaxError: Unexpected token ILLEGAL
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at /Users/humbleMouse/chapter02/node_modules/mocha/bin/_mocha:313:27
at Array.forEach (native)
at load (/Users/humbleMouse/chapter02/node_modules/mocha/bin/_mocha:310:9)
at Object.<anonymous> (/Users/humbleMouse/chapter02/node_modules/mocha /bin/_mocha:301:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
make: *** [test] Error 8
This is the test I am trying to run:
'use strict';
var assert = require('assert')
, should = require('should');
var exchangeData = {};
suite('exchange', function() {
test('buy should add a BUY nockmarket order', function(done) {
exchangeData = exchange.buy(40, 100, exchangeData);
exchangeData.buys.volumes[40].should.eql(100);
done();
});
test('sell should add a SELL nockmarket order', function(done) {
exchangeData = exchange.sell(41, 200, exchangeData);
exchangeData.sells.volumes['41'].should.eql(200); //this is line 22
done();
});

test('sell should produce trades', function(done) {
exchangeData = exchange.sell(40, 75, exchangeData);
exchangeData.trades[0].price.should.eql(40);
exchangeData.trades[0].volume.should.eql(75);
exchangeData.buys.volumes[40].should.eql(25);
exchangeData.sells.volumes[41].should.eql(200);
done();
});
});
There are some invalid characters in your code, if you used proper text editor, you'd see them. The line numbering is a bit off, but this is clearly the cause.
Here's a screenshot from Sublime Text:
It's \uFFFC, more info here.
Just delete them (they can't be seen, so delete all from the semicolon to the next test().

Reading files name that begin with DOT "."

i have this simple nodeJS script for reading files from a PATH and check if they are directory or not :
var fs = require("fs");
var allFiles = fs.readdirSync(__dirname + '/bb');
allFiles.forEach(function(name){
if(fs.lstatSync(name).isDirectory())
{
console.log(name);
}
});
The problem is when I check if the file is DIRECTORY .isDirectory() and the file begins with a DOT "."
fs.js:679
return binding.lstat(pathModule._makeLong(path));
^
Error: ENOENT, no such file or directory 'D:\test\.ggg'
at Object.fs.lstatSync (fs.js:679:18)
at D:\test\server.js:4:11
at Array.forEach (native)
at Object.<anonymous> (D:\test\server.js:3:10)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
If I don't check if DIRECTORY or the file name don't begin with a DOT "." it works just fine.
OS : Windows 7
You are calling .lstatSync with the wrong path.
Try path.join instead to create the correct path.
The snippet should look like
var fs = require("fs");
var allFiles = fs.readdirSync(__dirname + '/bb');
allFiles.forEach(function(name){
if(fs.lstatSync(path.join("bb",name)/*Correct path*/).isDirectory())
{
console.log(name);
}
});

How do I get html-snapshots to work?

I'm just trying to run html-snapshots. This should be easy, right?
This is what I started with:
npm install html-snapshots
That's all I need, right? Here's my snapshots.js file:
var htmlSnapshots = require('html-snapshots');
htmlSnapshots.run({
source: "sitemap.xml",
hostname: "localhost",
outputDir: "snapshots",
outputDirClean: true,
selector: "#results-widget"
});
And to run it:
node snapshots.js
But nooo:
module.js:340
throw err;
^
Error: Cannot find module '.\robots'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.module.exports.create (C:\webdev\node_modules\html-snapshots\lib\input-generators\index.js:38:16)
at Object.module.exports.run (C:\webdev\node_modules\html-snapshots\lib\html-snapshots.js:42:39)
at Object.<anonymous> (C:\webdev\snapshots.js:2:15)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
wtf?
Additional Info...
This is part of html-snapshots.js:
var inputFactory = require("./input-generators");
...
run: function(options, listener) {
...
var inputGenerator = inputFactory.create(options.input);
...
result = inputGenerator.run(options, (function(options, notifier){
Also, the html-snapshots\lib\input-generators folder contains the file robots.js
It looks like an issue inside html-snapshots\lib\input-generators\index.js file - it works fine on Linux systems but fails on Windows (path.sep has been used to build module name)
Problem is that it should load './robots' module instead of '.\robots'.
Quick fix is to update html-snapshots\lib\input-generators\index.js file - line 38.
Change line:
result = require(file);
to:
result = require(path.join(__dirname, file));
And it will work fine. I hope that will help.

Categories