fs.readFileSync(filePath, function read(err, data) {} does not work even tho the targeted file is in the correct location - node.js

Here's my relevant code:
1)
let pickenFile = randomItemFormatted.source_filenametxt;
let filePath = `textFiles/${pickenFile}`;
This happens after an axios.get() that returns the name of the file.
The problem does not come from the name of the file itself.
2)
fs.readFileSync(filePath, function read(err, data) {
if(err){
console.log(err);
runTheBot();
}else{
// I should be able to access the data here :(
console.log(data);
tokenizer = new natural.SentenceTokenizer();
let textToTokenize = tokenizer.tokenize(data.toString('utf8').replace(/\0/g, ''));
dataObj.randomItemFormatted = randomItemFormatted;
dataObj.stringsArray = textToTokenize;
return returnSpecificString(dataObj);
}
});
})}
When I pass the filePath to the fs.readFileSync(), the code does not pass the error block. I'm adding the full error response here:
(node:9500) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open 'textFiles/1884_Ford__Bradstreet.txt'
at Object.openSync (fs.js:447:3)
at Object.readFileSync (fs.js:349:35)
at /Users/cyrus/Documents/Code/01. Code/franklin-ford-bot/server_side/server.js:74:9
at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:9500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Here's also my project's architecture where the targeted .txt files are hosted.I start the server with the node server_side/server.js.
It was working previously and nothing changed in the code since when it was working.

fs.readFileSync() does not take a callback. Your code is trying to use the fs.readFile() interface with fs.readFileSync(). See the doc.
Errors from fs.readFileSync() will be thrown as exceptions so you need try/catch around it to catch errors.
The general structure for using fs.readFileSync() in the code you show would look like this:
try {
let data = fs.readFileSync(filePath);
// I should be able to access the data here :(
console.log(data);
tokenizer = new natural.SentenceTokenizer();
let textToTokenize = tokenizer.tokenize(data.toString('utf8').replace(/\0/g, ''));
dataObj.randomItemFormatted = randomItemFormatted;
dataObj.stringsArray = textToTokenize;
return returnSpecificString(dataObj);
} catch(e) {
console.log(e);
runTheBot();
return something;
}
Now, as for the ENOENT error, that is a separate problem to fix. What I would suggest is that you do this:
const path = require('path');
let filePath = `textFiles/${pickenFile}`
console.log(path.resolve(filePath));
This will show you the full path for the file you were attempting to use. It seems likely that either the full path is not exactly what you expected it to be or there is a file permission issue preventing you from accessing it.
If the textFiles subdirectory you are trying to access is below the module directory where this code is running from, then you may want to use __dirname to reference it like this:
const path = require('path');
let filePath = path.join(__dirname, "textFiles", pickenFile);

Related

TypeError: invNum.next is not a function

I have tried this code :
const invNum = require('invoice-number');
router.post('/checkout', async (req, res, next) => {
if (!req.session.cart) {
return res.redirect('/pos/');
}
var saleList = Sale.find().sort({ _id: -1 }).limit(1); // removed (err, data)=>{} to simply view it is working tested already
var settings = await Setting.find({}); // removed try and catch to simply view it is working tested already
var ticketNumber;
ticketNumber = !saleList ? invNum.next('0000000') : invNum.next(saleList.ticket_number);
var sale = new Sale({
ticket_number:ticketNumber,
cart: req.session.cart,
created_at: new Date()
});
sale.save((err, product) => {
createReceipt(settings, req.session.cart, "receipts/"+ticketNumber+".pdf");
req.session.cart = null;
res.redirect('/pos/');
});
});
I got this error:
TypeError: invNum.next is not a function
The problem is with invNum.next().
invNum.next() is a Node.js module to generate invoice number sequentially installed from npm.
Example:
invNum.next('2017/08/ABC001')
// => 2017/08/ABC002
I have tried already suggestions from previous stackoverflow posts by trying Promises or await async function in order to get this code to work. Hopefully, you can help or suggest something. Thank you.
There is a problem in version of invoice-number module. In the npm it is showing as 1.0.6 but in the GitHub repository it has 1.0.5 in the package.json file.
https://github.com/amindia/invoice-number.
I have tested this module by taking from Github repository and it's working fine.
Please take the source of this module from the given link it will works fine.
Seems to be some error in the module. I tried the below code snippet on RunKit
https://runkit.com/embed/ws2lv1y38mt4
var invNum = require('invoice-number')
try{
invNum.next('sdfsd1')
} catch(e){
console.log(e)
}
Getting the same error
I got this error:
TypeError: invNum.next is not a function UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
What is the output when you use the console.log on invNum?
Also use try catch and inside call invNum.next with await. Maybe something inside this function is throwing an error.
Edit: as jfriend00 says, if an plain text (like your "0000...") is working, probably the saleList is returning some error and you are not catching or treating the error.
Edit2: The last update on this NPM code is from 1 year ago and fewer people used this lib, probably is broken.
There is some part of the code from the index.js of the lib:
function _next (invoiceNumber) {
if (!invoiceNumber)
throw new Error('invoiceNumber cannot be empty')
var array = invoiceNumber.split(/[_/:\-;\\]+/)
var lastSegment = array.pop()
var priorSegment = invoiceNumber.substr(0, invoiceNumber.indexOf(lastSegment))
var nextNumber = alphaNumericIncrementer(lastSegment)
return priorSegment + nextNumber}
var api = { next: _next}
module.exports = api

NodeJs Require module returns an empty object

I'm using NodeJS 8 LTS.
I have 3 js scripts where:
// main.js
const dom = require ('./Domains/Domains');
const factory = require ('./Domains/Factory');
(async () => {
const Domain = await factory.foo(); // <=== Error
})();
// Domains.js
class Domains {
constructor (options = {}) {
....
}
}
module.exports = Domains;
// Factory.js
const Domains = require('./Domains');
module.exports = {
foo: async () =>{
.... async stuff ...
return new Domains();
}
};
when I run main.js I get
(node:1816) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Domains is not a constructor
warning.js:18
(node:1816) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Debugging, I found that in Factory.js when it requires Domanis.js const Domains = require('./Domains'); it returns an empty object.
Looking around on internet I found that it happens when there are a circular dependencies between modules (Require returns an empty object) but It doesn't seem the case here.
Any idea?
Finally, I got the the issue's origin. The empty object was due to a circular dependency derived by another require that was inside Domains.js
// Domains.js
const another_module= require("circular_dep_creator");
class Domains {
constructor (options = {}) {
....
}
}
module.exports = Domains;
// circular_dep_creator.js
const factory = require ('./Domains/Factory');
...
another stuff
So, this causes a circular dependency that creates an empty object
The setImmediate call will delay the loading of the required module until the browser has finished doing what it needs to do. This may cause some issues where you try to use this module before it is loaded, but you could add checks for that.
// produces an empty object
const module = require('./someModule');
// produces the required object
let module;
setImmediate(() => {
module = required('./someModule');
});

Module.exports not finding function

So I am creating a basic user login system (this is one of my first nodejs projects) and I am wanting to redirect the user to the 'dashboard' page with a successful login.
First of all I am not sure this is the best way to do the redirecting so I am open to suggestions.
The problem I am having is after calling the function and the user logs in I want to call this function:
var loginResponse = () =>{
io.emit('loginResponse');
}
This is in the server.js file (the main server file) and I am exporting it like so
module.exports = {
loginResponse : loginResponse
};
I am then after all the validation, calling db etc. is done wanting to call it in the login.js file as shown:
var createUserSession = (userSessionObj) =>{
session.user = userSessionObj;
serverMain.loginResponse();
};
I am requiring the file server file like so:
const serverMain = require('../server');
However, I am getting the following error on execute:
(node:35012) UnhandledPromiseRejectionWarning: TypeError: serverMain.loginResponse is not a function
at createUserSession (/Users/chrisholder/Documents/Programming/RandomPrograms/registerlogin/server/registrationlogin/login.js:83:14)
at hashing.comparePassword.then (/Users/chrisholder/Documents/Programming/RandomPrograms/registerlogin/server/registrationlogin/login.js:73:7)
at <anonymous>
(node:35012) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:35012) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I have tried using the 'path' module as another way to requiring the server.js file however, it has not worked.
Thanks for your help!

Replacing bluebird with node.js native promises breaks Promise.reject

The following code works perfectly fine when I use bluebird promises:
import * as Promise from 'bluebird';
getAccount(id) {
var account = find(accounts, ['id', id]);
return account ?
Promise.resolve(account) :
Promise.reject(new NotFoundError());
}
NotFoundError is defined as follows:
export function NotFoundError(message = 'Not Found') {
this.name = 'NotFoundError';
this.message = message;
this.stack = (new Error()).stack;
}
NotFoundError.prototype = Object.create(Error.prototype);
NotFoundError.prototype.constructor = NotFoundError;
However, if I remove the import of bluebird in getAccount() and let node.js take over promises, the code fails inside the NotFoundError() constructor because this is not defined. Specifically, the constructor is called twice, once correctly from the getAccount() code shown above and a second time by node.js's _tickCallback() function with this as undefined:
NotFoundError (errors.js:13)
runMicrotasksCallback (internal/proces…ext_tick.js:58)
_combinedTickCallback (internal/proces…ext_tick.js:67)
_tickCallback (internal/proces…ext_tick.js:98)
Why is node.js calling the NotFoundError() constructor a second time and that too incorrectly!!!
Please help.
The issue is caused by this line:
.catch(NotFoundError, function() { ... })
Native promises don't have an option to pass a specific error class to a catch method, so what happens is that when an error occurs, NotFoundError is called (without a new in front of it) because it's presumed to be the catch handler.

EPIPE write error html-pdf only on appfog server

I'm having a very weird EPIPE write error when I'm trying to generate a PDF from HTML with this module:
https://www.npmjs.com/package/html-pdf
The exact error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at errnoException (net.js:904:11)
at Object.afterWrite (net.js:720:19)
The line where I call the PDF gen:
var pdfgen = require("html-pdf");
pdfgen.create(html, options).toFile('whappbook.pdf', function(err, res) {
var errorCount = 0;
if (err) {
console.log(err);
errorCount++;
if(errorCount > 2) {
return console.log(err);
} else {
return create();
}
}
console.log(res); // { filename: '/app/businesscard.pdf' }
});
I've tried just using <h1>Testing</h1> as the HTML to see if the file was too big, but that wasn't the case.
Note: local everything works perfectly fine, but when I run this code on Appfog it doesn't work, so I suspect it has something to do with missing dependencies or file writing rights.
I'm writing directly to the home directory (in Appfog's case thats /app).
HTML-PDF is using PhantomJS and I've also directly npm'd that in my app because some people were reporting issues when it wasn't directly installed, but that didn't solve my problem either.
If there is any information that I can additionally provide please let me know!

Resources