Is there a way to load JS file without require? - javascript

Is there a way to load a javascript file without require, but with fs for example?
I know that for json files I can do:
const jsonFile = JSON.Parse(fs.readFileSync("./jsonfile.json")
Is there a way to do the same for a javascript file?
The reason I am asking is because, i have a configuration file that I kinda want to detach from my app, because when I bundle it with webpack, I cant exclude the config file.
I have tries to directly read it, but I just got some raw format in a buffer:
const jsFile = fs.readFileSync("./jsFile.js")
EDIT ANSWER: I was able to do it by utilizing readFileSync and eval:
const jsFile = eval(fs.readFileSync("./jsFile.js", "utf-8"));
Keep in mind that if you are requiring other files within that file, the paths change! They will NOT be relative to jsFile.js, but relative to the file which reads the jsFile.js

I was able to do it by utilizing readFileSync and eval:
const jsFile = eval(fs.readFileSync("./jsFile.js", "utf-8"));
Keep in mind that if you are requiring other files within that file, the paths change! They will NOT be relative to jsFile.js, but relative to the file which reads the jsFile.js

Related

Handling relative paths across modules in javascript

So let's say I have a .js file which exposes a function, which I want to be able to import in many other files. The function in this file needs access to some data stored in a certain file ( take .txt for this example) and I'm using the relative address to read and write to this text file.
Now the problem comes when I import this module into other files in different directories, the relative paths won't be valid but I don't know how I can change this? I'm sure there's a simple way to do this but I can't figure it out at all.
file 1
relative path = '../../file.txt'
function foo(){
fs.readFile(relativePath)
}
module.exports = {foo}
file 2
const {foo} = require('foo')
foo();
It doesn't actually matter which other modules load this module. The path is going to be resolved relative to the current working directory, which depends on in which directory your shell is in when you invoke the code.
If you want it to resolve relative to that specific JavaScript file, then you can use __dirname:
const path = require('path');
// ...
fs.readFile(path.join(__dirname, relativePath));
you can use resolve method of path package like
const path = require('path').resolve
path.resolve('../../file.txt')

NodeJS - Cant find JSON File

I'm working on a express API and i want to connect to a mysql server with this api. Settings are stored in a settings.json file. I read this using
const config = JSON.parse(require(`fs`).readFileSync('../../settings.json'));
This works if the json file is in the same directory. But in this case, the settings file is in the base directory(./settings.json) but the file from where i want it to access is: ./modules/sql/mysql.js. It doesnt work:
Error: ENOENT: no such file or directory, open '../../settings.json'
Is there a better way to access/read a json file? or what am i doing wrong?
Btw. i dont want to pass the settings as a variable. I already tried it but if possible - i want to avoid it.
File/Directory strcture
did you not miss a ../ there?
try replace '../../settings.json' for '../../../settings.json'
btw, its better to use the __dirname approach, but it should work just fine without that too :)

How to use ts file in external js file

How i can use a ts file in java script file.
I have an angular project in that i have a constant file which is environment.ts file and data is as below
export const Environment = {
PRODUCTION: false
};
and i have used one external java script library and in that library i want to access this environment.ts file i.e want to use constant.
i have tried with
var en = require('./environment.ts');
But not able to access it.
The problem probably comes from the fact that TS is compiled into JS during the build process.
Since you're just exporting the single object, it doesn't really need to be a typescript file.
Try to rename the file into 'environment.js', it shouldn't break anything and it will allow you to require it in other js files.
Try this,
import { Environment } from './environment';
Now we can access the properties like Environment.PRODUCTION
What I did is created dev.json and prod.json with my configurations.
I then imported dev.json into environment.ts and prod.json into environment.prod.ts for exporting to ts files.
I also imported dev.json into an environment.js and environment.prod.js for exporting to js files. You could also use the json directly if you want, but this will give you the flexibility to manipulate in js if you want later.
Now to update configs you just keep updating the json files.
Make sure your external js knows which env configs to read depending on how you're building/compiling it.

readFileSync is not a function

I am relatively new to Node.js and have been looking around but cannot find a solution. I did check the require javascript file and it does not seem to have a method for "readFileSync". Perhaps I don't have a proper require file? I had a hard time finding this file, everywhere talked about it but most people did not post where to get it.
I installed Node.js and have the require.js file. My current code is like this:
fs = require(['require'], function (foo) {
//foo is now loaded.
});
console.log("\n *STARTING* \n");
// Get content from file
var contents = fs.readFileSync("sliderImages", 'utf8');
I had a bit at first getting require to work however it seems to load the require JavaScript file. I have been following guides and I am not sure why I get this error:
Uncaught TypeError: fs.readFileSync is not a function
I have tried many fixes and cannot seem to figure this one out.
Node.js does not use Require.js. Require.js was built so that you could have asynchronous module loading on the client-side (in your browser).
Node.js uses CommonJS style modules. Your code using CommonJS would look like this:
var fs = require('fs');
console.log("\n *STARTING* \n");
var contents = fs.readFileSync("sliderImages", "utf8");
If we assume you saved this in a file called main.js you would then enter this command in your console (make sure you are in the same directory as the file):
node main.js
This code will not run in the browser. Node.js runs on the server. If you want to load a JSON file on the browser side then you'll need to load it using AJAX. There are numerous resources available to show you how to do this. Be aware that you must either run your page from a server or have a special flag enabled to load in files from the file system.
This error can arise if you write
const fs = import('fs');
in a Node module
but should write
import fs from 'fs';

I'd like to reuse code from another module in my Nodejs backend

I'm using the Yeoman Generator Angular Fullstack and I'd like to reuse JS code from different directories within my server directory. I'm referencing the file that has the functions I want like:
var something = require('/.path');
I get the error: "Cannot find module" in my terminal.
I tried a number of variations of the path working through all of the levels from server level down to file level where the given functions are contained. I looked at a few tutorials:
http://www.sitepoint.com/understanding-module-exports-exports-node-js/
AND
https://www.launchacademy.com/codecabulary/learn-javascript/node/modules
I clearly missed something. Each module of my nodejs has a controller with an exports.create function. All of my code for each module is contained within my exports.create function accept for other required modules. I have no problem requiring underscore or other libraries in my Node/Bower modules by the way.
To be as detailed as can be, I expected
var something = require('./directory/directory.controller.js');
var something = require('/.path');
The path you are using is likely incorrect. Probably you want to open the file called path.js contained in the same folder of the file from which you are importing it. In order to do that, you should change the import as follows :
var something = require('./path');
./path is a relative path where . stands for current directory.
/.path is an absolute path. In this case require is importing a hidden file in the root directory. I guess is not what you want.

Categories

Resources