Reputation: 75
Trying to use Dom-Parser with Discord.js. Couldn't find help from any where else.
Error on line 15 fs.readFile
I also had a lot problems getting fs working. First it wasn't defined then it could not be runned before initalization, just got that fixed (I hope)
// Discord stuff.
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require('./config.json');
const token = config.token;
// DomParser
var DomParser = require('dom-parser');
var parser = new DomParser();
var data = fs.readFileSync(filepathHidden);
// Other requirements
var fs = require('fs');
// when getting online.
client.once('ready', () => {
console.log('WAHAHAHA IM ALIVE!');
}),
fs.readFile('https://url.com)', 'utf8', function(err, html){
if (!err){
var dom = parser.parseFromString(html);
console.log(dom.getElementsByClassName('new_solution_box_title').innerHTML);
}
})
client.login(token);
Upvotes: 4
Views: 23023
Reputation: 437
In Node.js recent version (>=20.16.0)
, we could simply import, like that, import fs from 'fs'
. But for the lower version (<=18.14.0)
, we must have to import it like that: import * as fs from 'fs'
.
Upvotes: 0
Reputation: 1730
See answer for same error in another stack overflow question.
The link to the answer that helped me is from Arun Kumar Mohan
What he recommended was to import as follows: import * as fs from 'fs'
Upvotes: 18
Reputation: 3130
Please read NodeJS Documentation about URL object support for FS API. It seems that only file:
protocol is supported when using URLs.
However, I don't even recommend you to use fs.readFileSync
because it is a blocking operation (code execution will stop until it finishes) and there is a network transfer involved.
Try fetching the file first instead using fetch
, XMLHttpRequest
or your preferred library, and then parse it. Or at least use fs.readFile
which will perform its tasks asynchronously (file:
protocol limitation still applies).
For the non defined error, you must import/require fs
before using it. In other words, var fs = require('fs')
must appear before any other use of fs
.
Upvotes: 0
Reputation: 944005
var
is hoisted.
So since you have var fs
, there is a variable called fs
in the function / module / global scope where you have that statement.
It starts out undefined.
When you say fs = require('fs')
you assign the file system module to it. At that point it stops being undefined.
On the previous line when you try to read it with fs.readFileSync
, you haven't yet defined it so you get an error.
Order matters.
Upvotes: 5