How do I use node.js on a localhost:8000 server?

I have some pure JS code and HTML and CSS on my localhost:8000 server. I have installed node.js and I am able to use it without problem testing it on the VS code terminal. However, I want to integrate the file reading mechanic of node.js into the code that I am running on the localhost:8000 server. I want to put this node.js code into my webpage on localhost:8000

const {readFileSync, promises: fsPromises} = require('fs');
function syncReadFile(filename) {
const contents = readFileSync(filename, 'utf-8');

const arr = contents.split(/\r?\n/);

console.log(arr); // 👉️ ['One', 'Two', 'Three', 'Four']

return arr;
}

syncReadFile('./locations.txt');

I have tried copy and pasting it into the js file for the webpage, however when I run it, the console says

Uncaught ReferenceError: require is not defined
    at window.onload (index.js:23:46)

index.js:23:46 is the line where const {readFileSync, promises: fsPromises} = require('fs'); is.

How do I fix this?

Upvotes: 1

Views: 863

Answers (2)

Matt DF
Matt DF

Reputation: 71

I think you need a better understanding of how NodeJS works:

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

A JavaScript runtime is (in this context) a program that runs in a machine, with tools to interact with that machine. In development, the context of that machine is the context of a Server.

Now, JavaScript found it's use in the HTML script tag, that's the most "vanilla" way to execute JS in it's home, what it's most used for. In this context, JavaScript is running as a Client.

What makes NodeJS, different from executing the same code in an HTML file you can already execute without installing NodeJS? It's as vanilla as you can get after you "force" JavaScript to be executed in the Backend, but for it to be used as a webserver, there are some tools that need to be ported, converted or even created, some of these tools, like the File System (fs) are specific to NodeJS.

That's it! TLDR is that your code won't work because it's being executed in the wrong place. You can fix that in many ways, like this one, but maybe you can find a better path understanding how NodeJS works

Upvotes: 2

JustBarnt
JustBarnt

Reputation: 124

Browsers cannot access file systems like that. Nodefs will not work within the browser

Upvotes: 0

Related Questions