简体   繁体   中英

Error to read file from C drive with fs

I use the following code to read txt file from my C drive and I got error

fs = require('fs')


    var path = require('path');

    var filePath = path.join(__dirname, '‪C://nodeTest//test.txt');
    fs.readFile(filePath, 'utf8', function (err,data) {
        if (err) {
            return console.log(err);
        }

    });

in addition I try like following with the same error

fs.readFile('‪C://nodeTest//test.txt', 'utf8', function (err,data) {
        if (err) {
            return console.log(err);
        }

    });

error is

Error: ENOENT, open 'C:\nodeTest\test']
  errno: -4058,
  code: 'ENOENT',

My project is under the following path

C:\Users\C015869\WebstormProjects\myApp\server.js
  • Make sure the file exist with fs.existsSync('‪C://nodeTest//test.txt')
  • Make sure you have admin privilege. If you are on windows run Command Line as Administrator
  • Use single slash: var filePath = 'C:/nodeTest/test.txt'; or var filePath = path.join(__dirname, '‪test.txt')

You can only read from the webserver. If the file isn't somewhere in the webserver directory or subdirectories you can't read it. If the webserver directory is nodeTest then just use:

fs = require('fs')

var path = require('path');

var filePath = path.join(__dirname, '‪test.txt');
fs.readFile(filePath, 'utf8', function (err,data) {
    if (err) {
        return console.log(err);
    }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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