Importing a newly harvested array from a .js file (array that has been exported)

I followed this procedure with assistance from T.J to resolve my issue

To address the problem, I made changes to my process. The steps I took are as follows:

  • I switched from exporting an array through a JS file to saving a JSON file instead.
  • Using the .get() API, I read the file with fs.readFileSync(), parsed it with JSON.parse(), and returned the array in JSON format.

Here is the code snippet:

Arrays/bookFiles.json:

{
"name":"bookFiles",
"array":[["CSSNotesForProfessionals.pdf","/mnt/Data/Books/CSSNotesForProfessionals.pdf","pdf","application/pdf"],["JS for Beginners.pdf","/mnt/Data/Books/JS for Beginners.pdf","pdf","application/pdf"],["alqamoosulwaheed.pdf","/mnt/Data/Books/alqamoosulwaheed.pdf","pdf","application/pdf"]]
}

routes/book.mjs:

import express from "express";
import * as fs from 'fs'
export const book = express.Router();

book.get("/",(req,res)=>{
    const data = JSON.parse(fs.readFileSync('/home/abdurehman/LocalNas/backend/Arrays/bookFiles.json','utf-8'))
    res.send(data.array)
}
)

Previous Problem:

Below is the original array that gets modified by another script later on

export const bookFiles=[]

I imported this into my main Express JS + Node JS route for an API. However, there was an issue where the script retained the initial values of the array and provided those to the API fetch. Instead, I wanted it to re-import or re-scan the array before sending it to API fetch.

Router File: routes/book.mjs:

import express from "express";
export const book = express.Router();
import { bookFiles } from "../Arrays/bookFiles.mjs";

book.get("/",(req,res)=>{
    const data=bookFiles
    res.send(data)
}
)

This is my Main File /app.mjs:


import express from 'express';
import { zip } from './routes/zip.mjs';
import { office } from './routes/office.mjs';
import { compressed } from './routes/compressed.mjs';
import { image } from './routes/images.mjs';
import { book } from './routes/book.mjs';
import { videos } from './routes/videos.mjs';



var app = express()
app.use("/zipFiles",zip)
app.use("/officeFiles",office)
app.use("/videoFiles",videos)
app.use("/compressedFiles",compressed)
app.use("/bookFiles",book)
app.use("/imageFiles",image)

app.listen("5000")

I also attempted to readFileSync from .js file and then parse it into Array, but it didn't work due to JSON.parse() limitations. Thank you for your understanding.

As requested, here's the code responsible for changing the text of Arrays/*: /fmgr.mjs:

import * as fs from 'fs';
import {fileTypeFromFile} from 'file-type';
import * as path from 'path';
import * as url from 'url';

// The rest of the code remains the same...
...

Answer №1

Have you considered the benefits of using express.static middleware in your project?

If there is a need to access and process files, it may be more efficient to save them as .json files.

In case static files are not preferred...

Since you are already using JSON.stringify in your fs.writeFile function, have you thought about simplifying it by using:

fs.writeFile(__dirname + "Arrays/" + array.name + ".json", JSON.stringify(array.array), function (err) {

Answer №2

It appears that you have a web server process running, and there is another process that periodically updates the file ../Arrays/bookFiles.mjs. You are looking to display these changes.

However, JavaScript modules do not function in a way that allows for constant re-reading. Once a module is read during program execution, it does not update automatically.

If you need to read the file on each request or when it changes, consider making it a JSON file instead of a module. This way, you can rewrite the JSON file as needed and have your web process read and parse it upon startup or when changes occur. You could create a function that retrieves the array, caches it, tracks the file's date/time, and only re-reads the array if there are changes. Then, you can call this function in your route handler to return the updated array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate a custom event listener into my React Native component?

Hello everyone, I am currently working with React Native+Expo and have created a custom component called a stepper. Here's how it looks: Below is the code for this custom stepper: import React, { useState } from 'react'; import { View, Text ...

Learn the steps to invoke a JavaScript function from a <td> element within an ng-repeat loop

How can I call an Angular function inside ng-repeat td and replace the value from the function with the value in the td element? The code snippet provided below is not functioning as expected. Instead of getting the date, the same getCSTDateTime function i ...

PHP Error in Syntax

Earlier, I posted a question with a partial explanation. However, here is the complete version of my issue. I keep encountering a Syntax Error that gets resolved when I remove a specific block of code. There seems to be an underlying problem here, but desp ...

What is the best way to incorporate polling into the code provided below? I specifically need to retrieve data from the given URL every 60 seconds. How should I go about achieving this

Can you assist me in integrating polling into the code below? <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="https://code.highcharts.com/highcharts.js"> ...

What is the reason for using a wrapper with fs.readFile when a callback is included as an argument?

Recently delving into Node.js, I encountered a perplexing scenario while using fs.readFile(). Initially, my attempt to read a file led me to use: fs.readFile("file.txt",function(err,data) { if(err) {throw err;} console.log(data); }); However, to ...

Repetitive data in a list with AngularJS

There's probably a simple solution to this: I have some data in a controller, and depending on whether an item is selected or not, it should display different HTML. If the item is selected, the HTML should be: <li> <a href="#"><s ...

Utilizing the Loess npm module in conjunction with Angular 4

I am attempting to incorporate the Loess package into my project. The package can be found on NPM and offers various regression models for data fitting. I successfully installed it using npm install loess --save, and it now resides in the node_modules dire ...

I am struggling to decide which attribute to use for implementing image swap on mouseover() and mouseout()

I have a problem using jQuery to switch between images when hovering on and off. Here's the code snippet I'm working with: HTML <img class="commentImg" src="images/comments.png" data-swap="images/comment_hover.png" alt=""> jQuery $(" ...

Guide to decoding JSONP data sent from a remote server

Working on retrieving data using JSONP. After observing the returned data in Firebug, I can confirm that it is being returned correctly. However, I am facing a challenge in figuring out how to parse it. Is the data returning as a nested array? The callback ...

Over-extended Affix in Bootstrap 3.1.0

I'm currently using Bootstrap 3.1.0. The issue I've encountered is that when the "affix" becomes too long for the viewport, it ends up getting cut off and doesn't display the bottom items. Is there a way to make Bootstrap's affix featu ...

Guide to extracting the key of a JSON object with a numerical name

I am having trouble extracting JSON objects from my server that contain numbered names to distinguish them. When trying to retrieve these objects, I encounter an issue with appending numbers to the common name. The structure of the objects is as follows: ...

JQuery Datatables: Struggling to make JQuery function work following AJAX update

Watch this screencast to get a clearer understanding of the issue.... I'm currently working on my first project involving AJAX, and I'm encountering some obstacles. The datatable is loading user details from a JSON output using AJAX. Each row ...

Having difficulty deleting a checkbox element using JavaScript

My goal is to have a feature where users can effortlessly add or remove checkbox div elements as needed. The code I have written successfully adds and resets checkboxes, but I am encountering an issue when trying to remove them. I am struggling to identif ...

Slicing dynamic arrays in Numpy using minimum and maximum boundaries

Within my 3D array, shaped as (365, x, y), the axis corresponding to daily data contains instances where all elements are np.nan. The time series along the axis=0 takes on this form: https://i.stack.imgur.com/JAcHQ.png To identify the index of the peak ...

Enhance a collection by incorporating methods to the result of an angular resource query

After executing a query, I am left with an array from the resource: .factory('Books', function($resource){ var Books = $resource('/authors/:authorId/books'); return Books; }) I was wondering if there is a way to incorporate pr ...

Listening for a client's socket emit through Express Routes

I have successfully implemented the functionality to emit and receive messages using socket.io between the server and client with the code in server.js. const express = require('express') const app = express() const port = 4000 var http = require ...

Is there a way to redirect the results of the 'find' command into a pipeline that will trigger the execution of 'more' followed by 'grep' on the package.json file located two directories above?

I'm on a quest to identify the troublesome package.json file that is triggering a dependency warning. The warning originates from a sub-module, and I have employed a find command find . -name 'foo' to reveal its location. /a/very/very/very/ ...

What is the most effective method for populating data within a browser window?

I have a list of files stored in $scope.data that I retrieved from the searchFactory. Now, my goal is to display these files in the browser window. How can I accomplish this task? ctrl.js $scope.displayFiles = function (){ $window.open($scope.dat ...

Ensure your server stays alive and active with ReactPHP, just like the "pm2" process manager for "NodeJS"

I was recently taking a deep dive into learning about the fascinating world of "ReactPHP", but I ran into a bit of confusion regarding how to keep it running on the server in case of errors. After some research, I discovered that "NodeJS" has a handy tool ...

Efficiently Populating Arrays Without Blocking

Let's dive into the scenario... Here is the template for our component <template> <div> <loader v-show="loading"></loader> // display loading animation <div v-show="!loading"> <div v-for="group in groups ...