How to read file without require('fs') - NodeJS - node.js

I've got a challenge to read a txt file that located in the same directory as my app.js.
In the challenge I can't use require so I can't import fs.readFileSync to my app.
Looking for other ways to console.log the txt content. Any ideas?

Without using require explicitly, you can use: module.constructor._load or process.mainModule.constructor._load
const fs = module.constructor._load('fs');
console.log(fs.readFileSync('./test.txt'));
Note that process.mainModule will be undefined if there is no entry script. (Not your case)
Of course this shouldn't be used in production code, since it's an undocumented API and may change. But will do for your challenge.
forgot to mention that I have to run it as node app.js
Otherwise you could use ES6 modules too, but that requires an additional flag: node --experimental-modules app.js

Related

Type Error: require(..).load is not a function? [duplicate]

I am trying to replicate the import script to get my Firebase RTD data to Algolia. When trying to run the script, it fails and says dotenv.load is not a function.
I have the .env file in the same directory as the index.js file. I have tried moving the .env file around but that doesn't help. Here is the beginning code for the index.js:
const algoliasearch = require('algoliasearch');
const dotenv = require('dotenv');
const firebase = require('firebase');
//load values from the ./env file in this direcotry into process.env
dotenv.load();
//config firebase
firebase.initializeApp({
databaseURL: process.env.FIREBASE_DATABASE_URL,
});
What can I do? Using .config() on the requirement does not help either.
Based on NPM documentation you should use dotenv.config().
This worked for me:
require('dotenv').config({path:'my-app/.env'});
I right-clicked on the .env file to get the relative path.
Maybe it depends on the path of .env file and also, the way you are executing the script. Maybe the firebase commands to run (e.g., firebase serve --only functions) is different of to run node index.js in the path perspective (if you are using a cloud function).
In other words, you need to determine path of your main script and, then, determine the relative path of your .env file to this and set this path to dotenv.config().
To add on to #ahmad's answer, the documentation for the package asks to have you use dotenv.config() to load your .env file. Additionally depending on where you have the path, you'd pass the object { path: /path/to/your/file }. It would possibly help if you required the path package from the nodejs standard library to resolve paths to ensure you're getting the correct path to the file.

How to access .env file variables in TypeScript using dotenv?

I'm trying to use a .env file to store API keys in a TypeScript React project. My .env file is in the root of the project and I'm trying to access its variables from src/index.tsx via process.env.
.env:
FOO=foo
src/index.tsx:
import * as dotenv from "dotenv";
console.log(dotenv.config()); // prints TypeError: fs.readFileSync is not a function
console.log(process.env.FOO); // prints undefined
It looks like dotenv.config() throws in an error so I think that's where the problem is. Just not sure how to fix it. I've tried moving .env into the src directory and passing a path into the function, e.g. dotenv.config({ path: `${__dirname}/.env` }) but still getting the same error.
dotenv seems to be the most common way to use environment variables in a Node.js project, but if there are better alternatives I'd be interested in hearing those too.
Any thoughts & ideas would be appreciated.
Renaming the environment variable to REACT_APP_FOO and restarting react-scripts seems to do the trick. It works without calling dotenv.config(). Not really sure why it works this way so I would be interested to hear someone's insight on this.
You can access variables by first calling require('dotenv').config() at your project root. then you can use them like process.env.FOO.
You have to consider to call the process.env.FOO

dotenv module in node js return undefined

When i have written code for whatsapp boat using twilio module i get error in .env file
I have file structure like below:
/whatsappboatdemo
| app.js
| sendmsg.js
| .env
| package.json
And i have require dotenv like this in app.js file and sendmsg.js:
require('dotenv').config();
.env file content:
PORT=5000
TWILIO_ACCOUNT_SID=******************************
So when i run node app.js it gives undefined for process.env.PORT.
I have tried with different file structure but i don't get idea so please help me in this , thanks in advance :)
It is really hard to debug your issue with what you provided. I would advise to check 3 things as these are common errors:
Check if the format of the .env file is correct:
i.e.: PORT=9000 without any quotes etc.
Log the require call:
console.log(require('dotenv').config())
Try to set the path manually and check if it works:
require('dotenv').config({path: __dirname + '/.env'})
It might be nice to see how and when you require dotenv module.
Without further information I guess your error arise because when you are using your PORT variable, dotenv has not load it yet.
It is recommended to load dotenv module as soon as possible when loading your server.

"dotenv.load() is not a function" while trying to run a Node script

I am trying to replicate the import script to get my Firebase RTD data to Algolia. When trying to run the script, it fails and says dotenv.load is not a function.
I have the .env file in the same directory as the index.js file. I have tried moving the .env file around but that doesn't help. Here is the beginning code for the index.js:
const algoliasearch = require('algoliasearch');
const dotenv = require('dotenv');
const firebase = require('firebase');
//load values from the ./env file in this direcotry into process.env
dotenv.load();
//config firebase
firebase.initializeApp({
databaseURL: process.env.FIREBASE_DATABASE_URL,
});
What can I do? Using .config() on the requirement does not help either.
Based on NPM documentation you should use dotenv.config().
This worked for me:
require('dotenv').config({path:'my-app/.env'});
I right-clicked on the .env file to get the relative path.
Maybe it depends on the path of .env file and also, the way you are executing the script. Maybe the firebase commands to run (e.g., firebase serve --only functions) is different of to run node index.js in the path perspective (if you are using a cloud function).
In other words, you need to determine path of your main script and, then, determine the relative path of your .env file to this and set this path to dotenv.config().
To add on to #ahmad's answer, the documentation for the package asks to have you use dotenv.config() to load your .env file. Additionally depending on where you have the path, you'd pass the object { path: /path/to/your/file }. It would possibly help if you required the path package from the nodejs standard library to resolve paths to ensure you're getting the correct path to the file.

How to not bundle node_modules, but use them normally in node.js?

Architecture
I would like to share code between client and server side. I have defined aliases in the webpack config:
resolve: {
// Absolute paths: https://github.com/webpack/webpack/issues/109
alias: {
server : absPath('/src/server/'),
app : absPath('/src/app/'),
client : absPath('/src/client/'),
}
},
Problem
Now on the server side I need to include webpack in order to recognize the correct paths when I require a file. For example
require('app/somefile.js')
will fail in pure node.js because can't find the app folder.
What I need (read the What I need updated section)
I need to be able to use the webpack aliases. I was thinking about making a bundle of all the server part without any file from node_modules. In this way when the server starts it will use node_modules from the node_modules folder instead of a minified js file (Why? 1st: it doesn't work. 2nd: is bad, because node_modules are compiled based on platform. So I don't want my win files to go on a unix server).
Output:
Compiled server.js file without any node_modules included.
Let the server.js to use node_modules;
What I need updated
As I've noticed in https://github.com/webpack/webpack/issues/135 making a bundled server.js will mess up with all the io operation file paths.
A better idea would be to leave node.js server files as they are, but replace the require method provided with a custom webpack require which takes in account configurations such as aliases (others?)... Can be done how require.js has done to run on node.js server.
What I've tried
By adding this plugin in webpack
new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"ignore", /* filename= */"server.bundle.js")
Entries:
entry: {
client: "./src/client/index.js",
server: "./src/server/index.js",
ignore: ['the_only_node_module'] // But I need to do that for every node_module
},
It will create a file server.js which only contains my server code. Then creates a server.bundle.js which is not used. But the problem is that webpack includes the webpackJsonp function in the server.bundle.js file. Therefore both the client and server will not work.
It should be a way to just disable node_modules on one entry.
What I've tried # 2
I've managed to exclude the path, but requires doesn't work because are already minified. So the source looks like require(3) instead of require('my-module'). Each require string has been converted to an integer so it doesn't work.
In order to work I also need to patch the require function that webpack exports to add the node.js native require function (this is easy manually, but should be done automatically).
What I've tried # 3
In the webpack configuration:
{target: "node"}
This only adds an exports variable (not sure about what else it does because I've diffed the output).
What I've tried # 4 (almost there)
Using
require.ensure('my_module')
and then replacing all occurrences of r(2).ensure with require. I don't know if the r(2) part is always the same and because of this might not be automated.
Solved
Thanks to ColCh for enlighten me on how to do here.
require = require('enhanced-require')(module, require('../../webpack.config'));
By changing the require method in node.js it will make node.js to pass all requires trough the webpack require function which allow us to use aliases and other gifts! Thanks ColCh!
Related
https://www.bountysource.com/issues/1660629-what-s-the-right-way-to-use-webpack-specific-functionality-in-node-js
https://github.com/webpack/webpack/issues/135
http://webpack.github.io/docs/configuration.html#target
https://github.com/webpack/webpack/issues/458
How to simultaneously create both 'web' and 'node' versions of a bundle with Webpack?
http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/
Thanks
Thanks to ColCh for enlighten me on how to do here.
require = require('enhanced-require')(module, require('../../webpack.config'));
By changing the require method in node.js it will make node.js to pass all requires trough the webpack require function which allow us to use aliases and other gifts! Thanks ColCh!
My solution was:
{
// make sure that webpack will externalize
// modules using Node's module API (CommonJS 2)
output: { ...output, libraryTarget: 'commonjs2' },
// externalize all require() calls to non-relative modules.
// Unless you do something funky, every time you import a module
// from node_modules, it should match the regex below
externals: /^[a-z0-9-]/,
// Optional: use this if you want to be able to require() the
// server bundles from Node.js later
target: 'node'
}

Resources