Home > Software design >  Why is copyFileSync() copying a blank file?
Why is copyFileSync() copying a blank file?

Time:10-29

I am trying to generate identifiers for my Post model using a text file which I achieved successfully.

When I go to delete a Post I have to shift all postId -1.

I do this because in my template I am iterating through the posts and I have a postIdentifier variable that maps to that specific post so when a post gets deleted I must shift all postId's minus 1 so the postIdentifier variable properly matches to the specific post to edit or delete.

NOTE: I am trying to maintain both the text file and the database with the postIds shifted -1.

The issue I am dealing with is copying the contents of one file to another.

When I try to copy fileSystem.copyFileSync(constantVariable.FILE_PATH_TO_POST_SHIFT_IDENTIFIERS, constantVariable.FILE_PATH_POST_IDENTIFIERS). it copies a blank file even though there is content in it.

I decided to try to switch the source and destination variables around and it works that way but this is not what I want.

Why is copyFileSync() copying a blank file?

/* deletePost.js */

var express = require('express');
const Post = require("../models/post")
const Account = require("../models/account")
const sessionStorage = require("sessionstorage")
const constantVariable = require("../public/javascripts/constantVariables")
const fileSystem = require("fs")
var router = express.Router();

/* GET delete post page. */
router.get('/:postId', function(req, res, next) {
    var numberId = Number(req.params.postId)

    // Collect the identifier so we can delete the specific instance later.
    sessionStorage.setItem("deleteIdentifier", numberId)
    Post.findOne({postId: numberId}).exec(function(err, post) {
        Account.findOne({email: req.session.email}).exec(function(err, account) {
            res.render("deletePost", { title: "Social Application", post: post, account: account})
        })
    })
});

/* POST delete post */
router.post("/", function(req, res, next) {
    Post.findOneAndRemove({postId: sessionStorage.getItem("deleteIdentifier")}, function(err, post) {
        if (err) {
            console.log(err)
        } else {
            console.log("Removed post: "   post)
        }
    })

    // Get the file contents then find and replace identifier.
    var postIdentifiers = fileSystem.readFileSync(constantVariable.FILE_PATH_POST_IDENTIFIERS, {encoding: "utf-8"})
    var newValue = postIdentifiers.replace(sessionStorage.getItem("deleteIdentifier").toString(), "")

    // Write the replacement value to the file.
    fileSystem.writeFileSync(constantVariable.FILE_PATH_POST_IDENTIFIERS, newValue)

    // Write all the contents from postIds.txt to postShiftIds.txt - 1.
    var readable = fileSystem.createReadStream(constantVariable.FILE_PATH_POST_IDENTIFIERS, {encoding: "utf-8"})

    readable.on("readable", function() {
        var id = ""
        var parsedId = 0
        var shiftedId = 0

        while ((id = readable.read(1)) !== null) {
            parsedId = parseInt(id)
            if (parsedId !== 0) {
                parsedId -= 1
                shiftedId = parsedId
            }
            
            // Write the shifted identifier to postShiftIds.txt - 1.
            fileSystem.appendFileSync(constantVariable.FILE_PATH_TO_POST_SHIFT_IDENTIFIERS, shiftedId.toString())
        }
    })

    // Copy the shifted identifiers to the original file.
    fileSystem.copyFileSync(constantVariable.FILE_PATH_TO_POST_SHIFT_IDENTIFIERS, constantVariable.FILE_PATH_POST_IDENTIFIERS)
    
    // Shift all the post identifiers down one.
    Post.find({}).exec(function(err, posts) {
        if (err) {
            console.log(err)
        } else {
            var package = {}
            posts.forEach((post) => {
                // Dont subtract the first id.
                if (post.postId === 0) {
                    package = {
                        postId: post.postId,
                        emailId: post.emailId,
                        postTitle: post.postTitle,
                        postMessage: post.postMessage
                    }
                } else {
                        package = {
                        postId: post.postId - 1,
                        emailId: post.emailId,
                        postTitle: post.postTitle,
                        postMessage: post.postMessage
                    }
                }
                
                Post.findOneAndUpdate({postId: post.postId}, package, {new: true}, function(err, post) {
                    if (err) {
                        console.log(err)
                    } else {
                        console.log("Shifted index: ", post)
                    }
                })
            })
        }
    })
    
    res.redirect("allPosts")
})
/* allPosts.pug */

extends mainApplicationLayout

block content 

    - var accountEmail = ""
    - var emailId = ""
    - var pathToEditPost = ""
    - var pathToDeletePost = ""
    - var postIdentifier = 0

    each account in accounts 
        - accountEmail = account.email 
        each post in posts
            - emailId = post.emailId 

            //- If the unique email address from the account matches the email id of the post then we will display that information.
            if (emailId === accountEmail)
                br
                div(class="container")
                    div(class="jumbotron")
                        p(class="float-end text-muted")= post.datePosted.toLocaleDateString()
                    
                        img(src=account.accountPhoto class="rounded-circle" width="80" height="80" alt="Profile photo")
                        h5= account.name   " "   account.lastName
                    
                        hr
                        div(class="container")
                            h5: b #{post.postTitle} 
                            p(class="text-muted")= post.postMessage
                        hr
                        p(class="float-end text-muted")= post.datePosted.toLocaleTimeString("en-US", {hour: '2-digit', minute: '2-digit'})

                        - pathToEditPost = "/editPost"   '/'   postIdentifier.toString()
                        - pathToDeletePost = "/deletePost"   '/'   postIdentifier.toString()

                        //- Increment the index for post identifers.
                        - postIdentifier  = 1

                        a(href=pathToEditPost class="float-start"): button(class="btn-sm btn-primary mx-1") Edit post
                        a(href=pathToDeletePost class="text-danger float-start"): button(class="btn-sm btn-danger mx-1") Delete post
                        br
                br
    br

CodePudding user response:

I would put a log in right before the copy command:

// Copy the shifted identifiers to the original file.
console.log(
  'ARGUMENTS',
  constantVariable.FILE_PATH_TO_POST_SHIFT_IDENTIFIERS,
  constantVariable.FILE_PATH_POST_IDENTIFIERS,
);
fileSystem.copyFileSync(
  constantVariable.FILE_PATH_TO_POST_SHIFT_IDENTIFIERS, 
  constantVariable.FILE_PATH_POST_IDENTIFIERS,
);

and then I would read in the console what is being passed in, and then maybe try same thing in the node repl:

$ node
> const fileSystem = require("fs");
> fileSystem.copyFileSync(... arguments from log);

and then see if the file gets copied where you want it. You might figure out the issue in either step

CodePudding user response:

All I had to do was move the fileSystem.appendFileSync(constantVariable.FILE_PATH_TO_POST_SHIFT_IDENTIFIERS, shiftedId.toString())

to a different spot here is what it looks like now:

/* deletePost.js */

/* POST delete post */
router.post("/", function(req, res, next) {
    Post.findOneAndRemove({postId: sessionStorage.getItem("deleteIdentifier")}, function(err, post) {
        if (err) {
            console.log(err)
        } else {
            console.log("Removed post: "   post)
        }
    })

    // Get the file contents then find and replace identifier.
    var postIdentifiers = fileSystem.readFileSync(constantVariable.FILE_PATH_POST_IDENTIFIERS, {encoding: "utf-8"})
    var newValue = postIdentifiers.replace(sessionStorage.getItem("deleteIdentifier").toString(), "")

    // Write the replacement value to the file.
    fileSystem.writeFileSync(constantVariable.FILE_PATH_POST_IDENTIFIERS, newValue)

    // Write all the contents from postIds.txt to postShiftIds.txt - 1.
    var readable = fileSystem.createReadStream(constantVariable.FILE_PATH_POST_IDENTIFIERS, {encoding: "utf-8"})

    readable.on("readable", function() {
        var id = ""
        var parsedId = 0
        var shiftedId = 0

        while ((id = readable.read(1)) !== null) {
            parsedId = parseInt(id)
            if (parsedId !== 0) {
                parsedId -= 1
                shiftedId = parsedId
            }
            
            // Write the shifted identifier to postShiftIds.txt - 1.
            fileSystem.appendFileSync(constantVariable.FILE_PATH_TO_POST_SHIFT_IDENTIFIERS, shiftedId.toString())
        }
        // ********************** [NEW LOCATION] **********************
        // Copy the shifted identifiers to the original file.
        fileSystem.copyFileSync(constantVariable.FILE_PATH_TO_POST_SHIFT_IDENTIFIERS, constantVariable.FILE_PATH_POST_IDENTIFIERS)
    })
    
    // Shift all the post identifiers down one.
    Post.find({}).exec(function(err, posts) {
        if (err) {
            console.log(err)
        } else {
            var package = {}
            posts.forEach((post) => {
                // Dont subtract the first id.
                if (post.postId === 0) {
                    package = {
                        postId: post.postId,
                        emailId: post.emailId,
                        postTitle: post.postTitle,
                        postMessage: post.postMessage
                    }
                } else {
                        package = {
                        postId: post.postId - 1,
                        emailId: post.emailId,
                        postTitle: post.postTitle,
                        postMessage: post.postMessage
                    }
                }
                
                Post.findOneAndUpdate({postId: post.postId}, package, {new: true}, function(err, post) {
                    if (err) {
                        console.log(err)
                    } else {
                        console.log("Shifted index: ", post)
                    }
                })
            })
        }
    })
    
    res.redirect("allPosts")
})

module.exports = router;
  • Related