简体   繁体   English

在路径Node.js上删除文件

[英]Remove file at path Node.js

I am learning to build API by myself. 我正在学习自己构建API。 I was wondering how to delete a file that stored physical hard drive. 我想知道如何删除存储物理硬盘的文件。 I have read a post that I can use fs.unlink for this job. 我读了一篇文章,我可以使用fs.unlink来完成这项工作。 In order to that, I need a path. 为此,我需要一条路。

First of all, this is my file structure: 首先,这是我的文件结构:

root_folder
        ->api (folder)
             -> models (folder)
                      -> product.js

             -> route (folder)
                      -> products.js
        ->node_modules
        ->uploads (image folder)
        ->app.js (main js file)
        ->nodemon.json
        ->package.json
        ->package-lock.json
        ->server.js

These are my model & route files: 这些是我的模型和路线文件:

product.js (model file) product.js (模型文件)

const mongoose = require('mongoose');

const productSchema =  mongoose.Schema({
     _id: mongoose.Schema.Types.ObjectId,
     name: {type: String, require: true},
     price: {type: Number, require: true},
     productImage: {type: String, require: true}
});

module.exports =  mongoose.model('Product', productSchema);

products.js (route file) products.js (路由文件)

router.delete('/:productId', (req, res, next) => {
const id = req.params.productId;
Product.deleteOne({_id: id})
    .exec()
    .then(result => {
        res.status(200).json({
            message: 'Product Deleted' + test,
            request: {
                type: 'POST',
                url: 'http://localhost:3000/products/', 
                body: {name: 'String', price: 'Number', productImage: 'String'}
            }
        });
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            err: err
        });
    });
});

module.exports = router;

Stored data as an example: 以存储的数据为例:

{
    "product": {
         "_id": "5b8699c02c457856d08a2084",
         "name": "asdasdasd",
         "price": 12.1,
         "productImage": "uploads\\1535547840473pp.png"
    },
    "request": {
         "type": "GET",
         "url": "http://localhost:3000/products/5b8699c02c457856d08a2084"
    }

}

Here, it is my question. 在这里,这是我的问题。 I want to access the file path that I uploaded. 我想访问我上传的文件路径。 I am holding the path in productImage . 我在productImage持有路径。 As I wrote, I could not access. 如我所写,我无法访问。 How can I do it because I want to delete the file? 我要删除文件,该怎么办?

Help of @ArtemArkhipov in this Post the real solution while getting the path and deleting both entry and physical stored file. @ArtemArkhipov在本文中的帮助在获取路径并删除条目和物理存储文件的同时发布真正的解决方案。

Router.delete('/:productId', checkAuth, (req, res, next) => {
  const id = req.params.productId;
  var imageName = "";

  Product.findById(id)
    .select('productImage')
    .exec()
    .then(docs => {
      imageName = docs.productImage;
      fs.unlinkSync(__rootdir + "\\" + imageName);
      console.log(docs.productImage); // by the way you had misspell here
      return Product.deleteOne({_id: id}).exec();
    })
    .then(() => {
      res.status(200).json({
        message: 'Product Deleted',
        request: {
          type: 'POST',
          url: 'http://localhost:3000/products/',
          body: {
            name: 'String',
            price: 'Number',
            productImage: 'String'
          }
        }
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM