JavaScript read file

60 JavaScript code examples are found related to "read file".
Example 1
Source File: readFile.js    From express-jsdoc-swagger with MIT License 8 votes vote down vote up
readFile = path => (
  new Promise((resolve, reject) => {
    let data = '';
    const readStream = fs.createReadStream(path, 'utf8');
    readStream.on('data', chunk => {
      data += chunk;
    })
      .on('end', () => resolve(data))
      .on('error', error => reject(error));
  })
)
Example 2
Source File: ignored-paths.js    From cybsec with GNU Affero General Public License v3.0 8 votes vote down vote up
/**
     * read ignore filepath
     * @param {string} filePath, file to add to ig
     * @returns {Array} raw ignore rules
     */
    readIgnoreFile(filePath) {
        if (typeof this.cache[filePath] === "undefined") {
            this.cache[filePath] = fs.readFileSync(filePath, "utf8").split(/\r?\n/gu).filter(Boolean);
        }
        return this.cache[filePath];
    }
Example 3
Source File: utils.js    From speech-to-text-code-pattern with Apache License 2.0 8 votes vote down vote up
readFileToArrayBuffer = fileData => {
  const fileReader = new FileReader();

  return new Promise((resolve, reject) => {
    fileReader.onload = () => {
      const arrayBuffer = fileReader.result;
      resolve(arrayBuffer);
    };

    fileReader.onerror = () => {
      fileReader.abort();
      reject(new Error('failed to process file'));
    };

    // Initiate the conversion.
    fileReader.readAsArrayBuffer(fileData);
  });
}
Example 4
Source File: readFileAsText.js    From ehr with GNU Affero General Public License v3.0 8 votes vote down vote up
export default function readFileAsText(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = () => {
            resolve(reader.result);
        };

        reader.onerror = () => {
            reject(reader.error);
            reader.abort();
        };

        reader.readAsText(file);
    });
}
Example 5
Source File: util.js    From ux-http-server with MIT License 8 votes vote down vote up
function readFileP(file, charset) {
    return makePromise(charset ? function(callback) {
        return fs.readFile(file, function(err, data) {
            if (err) {
                callback(err);
            } else {
                callback(null, iconv.decode(data, charset));
            }
        });
    } : function(callback) {
        return fs.readFile(file, "utf8", callback);
    });
}
Example 6
Source File: utils.js    From kucoin-node-sdk with Apache License 2.0 8 votes vote down vote up
async function readFile(filePath) {
  const fileAbsolutePath = path.join(__dirname, filePath);
  // console.log(fileAbsolutePath);
  const readStream = fs.createReadStream(fileAbsolutePath);
  let chunk = "";
  return new Promise((resolve) => {
    readStream.on('data', data => {
      chunk += data;
    });
    readStream.on('end', () => {
      resolve(chunk);
    });
    readStream.on('error', (err) => {
      resolve(err.message);
    });
  });
}
Example 7
Source File: folder.js    From ke-ve with MIT License 8 votes vote down vote up
function readPackage(file, force = false) {
  if (!force) {
    const cachedValue = pkgCache.get(file);
    if (cachedValue) {
      return cachedValue;
    }
  }
  const pkgFile = path.join(file, 'package.json');
  if (fs.existsSync(pkgFile)) {
    const pkg = fs.readJsonSync(pkgFile);
    pkgCache.set(file, pkg);
    return pkg;
  }
}
Example 8
Source File: utils.js    From dshop with MIT License 8 votes vote down vote up
/**
 * Returns a shop's mock products.
 * @returns {Promise<void>}
 */
async function mockReadProductsFileFromWeb() {
  return [
    {
      id: 'iron-mask',
      externalId: 194464746,
      title: 'Mandalorian mask',
      price: 25000,
      image: '46c08ceaf67605b978f128b2b9153ac7.jpg'
    }
  ]
}
Example 9
Source File: common.js    From paras-landing with GNU General Public License v3.0 8 votes vote down vote up
readFileAsUrl = (file) => {
	const temporaryFileReader = new FileReader()

	return new Promise((resolve) => {
		temporaryFileReader.onload = () => {
			resolve(temporaryFileReader.result)
		}
		temporaryFileReader.readAsDataURL(file)
	})
}
Example 10
Source File: common.js    From paras-landing with GNU General Public License v3.0 8 votes vote down vote up
readFileDimension = (file) => {
	const temporaryFileReader = new FileReader()

	return new Promise((resolve) => {
		temporaryFileReader.onload = () => {
			const img = new Image()

			img.onload = () => {
				resolve({
					width: img.width,
					height: img.height,
				})
			}

			img.src = temporaryFileReader.result
		}
		temporaryFileReader.readAsDataURL(file)
	})
}
Example 11
Source File: utils.js    From OC-Mentors-AccountAddon with MIT License 8 votes vote down vote up
readFile = function readFile(_path, _cb){

    console.info('Reading:', _path);

    return fetch(_path, {mode:'same-origin'})   // <-- important

    .then(function(_res) {
        return _res.blob();
    })

    .then(function(_blob) {
        var reader = new FileReader();

        reader.addEventListener("loadend", function() {
            _cb(this.result);
        });

        reader.readAsText(_blob); 
    });
}
Example 12
Source File: readFileList.js    From cs-wiki with GNU General Public License v3.0 8 votes vote down vote up
// docs文件路径

function readFileList(dir = docsRoot, filesList = []) {
  const files = fs.readdirSync(dir);
  files.forEach( (item, index) => {
      let filePath = path.join(dir, item);
      const stat = fs.statSync(filePath);
      if (stat.isDirectory() && item !== '.vuepress') {
        readFileList(path.join(dir, item), filesList);  //递归读取文件
      } else {
        if(path.basename(dir) !== 'docs'){ // 过滤docs目录级下的文件

          const fileNameArr = path.basename(filePath).split('.')
          let name = null, type = null;
          if (fileNameArr.length === 2) { // 没有序号的文件
            name = fileNameArr[0]
            type = fileNameArr[1]
          } else if (fileNameArr.length === 3) { // 有序号的文件
            name = fileNameArr[1]
            type = fileNameArr[2]
          } else { // 超过两个‘.’的
            log(chalk.yellow(`warning: 该文件 "${filePath}" 没有按照约定命名,将忽略生成相应数据。`))
            return
          }
          if(type === 'md'){ // 过滤非md文件
            filesList.push({
              name,
              filePath
            });
          }

        }
      }        
  });
  return filesList;
}
Example 13
Source File: utils.js    From Chuck with MIT License 8 votes vote down vote up
readFile = async (path, encoding = 'utf8') => {
    return new Promise((resolve, reject) => {
        fs.readFile(path, (err, data) => {
            if (err) {
                return reject(err);
            }
            resolve(data.toString(encoding));
        });
    });
}
Example 14
Source File: util.js    From after-effects-to-blender-export with MIT License 8 votes vote down vote up
function readTextFile(fileOrPath) {
    var filePath = fileOrPath.fsName || fileOrPath;
    var file = new File(filePath);
    function check() {
        if (file.error) throw new Error('Error reading file "' + filePath + '": ' + file.error);
    }
    try {
        file.open('r'); check();
        file.encoding = 'UTF-8'; check();
        var result = file.read(); check();
        return result;
    } finally {
        file.close(); check();
    }
}
Example 15
Source File: util.js    From after-effects-to-blender-export with MIT License 8 votes vote down vote up
function readSettingsFile(version) {
    try {
        var settings = JSON.parse(readTextFile(settingsFilePath));
        if (version === settings.version) return settings;
        return null;
    } catch (e) {
        return null;
    }
}
Example 16
Source File: fileUtils.js    From audiobookshelf with GNU General Public License v3.0 8 votes vote down vote up
async function readTextFile(path) {
  try {
    var data = await fs.readFile(path)
    return String(data)
  } catch (error) {
    Logger.error(`[FileUtils] ReadTextFile error ${error}`)
    return ''
  }
}
Example 17
Source File: file-util.js    From ain-blockchain with MIT License 8 votes vote down vote up
static async readChunkedJsonAsync(filePath) {
    const LOG_HEADER = 'readChunkedJsonAsync';
    try {
      return new Promise((resolve) => {
        const transformStream = JSONStream.parse('docs.*');
        const chunks = [];
        let numChunks = 0;
        fs.createReadStream(filePath)
          .pipe(zlib.createGunzip())
          .pipe(transformStream)
          .on('data', (data) => {
            logger.debug(`[${LOG_HEADER}] Read chunk[${numChunks}]: ${JSON.stringify(data)}`);
            chunks.push(data);
            numChunks++;
          })
          .on('end', () => {
            logger.debug(
                `[${LOG_HEADER}] Reading ${chunks.length} chunks done.`);
            resolve(FileUtil.buildObjectFromChunks(chunks));
          })
          .on('error', (e) => {
            logger.error(`[${LOG_HEADER}] Error while reading ${filePath}: ${e}`);
            resolve(null);
          });
      });
    } catch (err) {
      logger.error(`[${LOG_HEADER}] Error while reading ${filePath}: ${err}`);
      return null;
    }
  }
Example 18
Source File: file-util.js    From ain-blockchain with MIT License 8 votes vote down vote up
static readChunkedJsonSync(filePath) {
    const LOG_HEADER = 'readChunkedJsonSync';
    try {
      const zippedFs = fs.readFileSync(filePath);
      return FileUtil.buildObjectFromChunks(JSON.parse(zlib.gunzipSync(zippedFs).toString()).docs);
    } catch (err) {
      logger.error(`[${LOG_HEADER}] Error while reading ${filePath}: ${err}`);
      return null;
    }
  }
Example 19
Source File: file-util.js    From ain-blockchain with MIT License 8 votes vote down vote up
static readCompressedJsonSync(filePath) {
    const LOG_HEADER = 'readCompressedJsonSync';
    try {
      const zippedFs = fs.readFileSync(filePath);
      return JSON.parse(zlib.gunzipSync(zippedFs).toString());
    } catch (err) {
      logger.error(`[${LOG_HEADER}] Error while reading ${filePath}: ${err}`);
      return null;
    }
  }
Example 20
Source File: file-util.js    From ain-blockchain with MIT License 8 votes vote down vote up
static readJsonSync(filePath) {
    const LOG_HEADER = 'readJsonSync';
    try {
      const fileStr = fs.readFileSync(filePath);
      return JSON.parse(fileStr);
    } catch (err) {
      logger.error(`[${LOG_HEADER}] Error while reading ${filePath}: ${err}`);
      return null;
    }
  }
Example 21
Source File: file-util.js    From ain-blockchain with MIT License 8 votes vote down vote up
static readH2nFile(chainPath, blockHash) {
    const LOG_HEADER = 'readH2nFile';
    const h2nPath = FileUtil.getH2nPath(chainPath, blockHash);
    try {
      return Number(fs.readFileSync(h2nPath).toString());
    } catch (err) {
      logger.error(`[${LOG_HEADER}] Error while reading ${h2nPath}: ${err}`);
      return -1;
    }
  }
Example 22
Source File: utils.js    From html-canvas with MIT License 8 votes vote down vote up
/**
 * 读取 json
 */
function readJson(filePath) {
  try {
    // eslint-disable-next-line import/no-dynamic-require
    const content = require(filePath)
    delete require.cache[require.resolve(filePath)]
    return content
  } catch (err) {
    return null
  }
}
Example 23
Source File: utils.js    From html-canvas with MIT License 8 votes vote down vote up
/**
 * 读取文件
 */
async function readFile(filePath) {
  try {
    return await readFileSync(filePath, 'utf8')
  } catch (err) {
    // eslint-disable-next-line no-console
    return console.error(err)
  }
}
Example 24
Source File: json-files.js    From testnet-faucet2 with MIT License 8 votes vote down vote up
// Read and parse a JSON file.
function readJSON (fileName) {
  return new Promise(function (resolve, reject) {
    try {
      fs.readFile(fileName, (err, data) => {
        if (err) {
          if (err.code === 'ENOENT') {
            console.log('Admin .json file not found!')
          } else {
            console.log(`err: ${JSON.stringify(err, null, 2)}`)
          }

          return reject(err)
        }

        const obj = JSON.parse(data)

        return resolve(obj)
      })
    } catch (err) {
      console.error('Error trying to read JSON file in util.js/_readJSON().', err)
      return reject(err)
    }
  })
}
Example 25
Source File: image.js    From nextjs-ic-starter with MIT License 8 votes vote down vote up
async function readFileToArrayBuffer(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader()

    reader.onload = () => {
      resolve(reader.result)
    }

    reader.onerror = reject
    reader.readAsArrayBuffer(file)
  })
}
Example 26
Source File: magic.js    From jscool with MIT License 8 votes vote down vote up
readFileSync(path) {
        try {
            return fs.readFileSync(path).toString();
        } catch (e) {
            console.log(path, '文件不存在进行创建')
            this.writeFileSync(path, '');
            return '';
        }
    }
Example 27
Source File: helper.js    From cd_pnp with MIT License 8 votes vote down vote up
async function read_file(file) {
    return await new Promise((resolve, reject) => {
        let reader = new FileReader();

        reader.onload = () => {
            resolve(new Uint8Array(reader.result));
        };
        reader.onerror = reject;
        reader.readAsArrayBuffer(file);
    })
}
Example 28
Source File: helper.js    From cdbus_gui with MIT License 8 votes vote down vote up
async function read_file(file) {
    return await new Promise((resolve, reject) => {
        let reader = new FileReader();

        reader.onload = () => {
            resolve(new Uint8Array(reader.result));
        };
        reader.onerror = reject;
        reader.readAsArrayBuffer(file);
    })
}
Example 29
Source File: utils.js    From easychess with MIT License 8 votes vote down vote up
function readFile(file, method){
    return P(resolve=>{
        let reader = new FileReader()

        reader.onload = event => {          
            resolve(event)
        }

        reader[method](file)                
    })
}
Example 30
Source File: utils.js    From easychess with MIT License 8 votes vote down vote up
function readFile(file, method){
    return P(resolve=>{
        let reader = new FileReader()

        reader.onload = event => {          
            resolve(event)
        }

        reader[method](file)                
    })
}
Example 31
Source File: config.js    From homebridge-petkit-feeder-mini with Apache License 2.0 8 votes vote down vote up
static readStoragedConfigFromFile(filePath, errlog) {
        var result = undefined;
        try {
            // const filePath = api.user.storagePath() + '/raspberry-simplegpio.json';
            if (fs.existsSync(filePath)) {
                const rawdata = fs.readFileSync(filePath);
                const accessory_name = this.config.get('name');
                if (JSON.parse(rawdata)[accessory_name] !== undefined) {
                    result = JSON.parse(rawdata)[accessory_name];
                }
            }
        } catch (error) {
            errlog('readstoragedConfigFromFile failed: ' + error);
        } finally {
            return result;
        }
    }
Example 32
Source File: utils.js    From react-perspective-cropper with MIT License 8 votes vote down vote up
readFile = (file) => {
  if (file instanceof File) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = (event) => {
        resolve(reader.result)
      }
      reader.onerror = (err) => {
        reject(err)
      }
      reader.readAsDataURL(file)
    })
  }
  if (typeof file === 'string') {
    return Promise.resolve(file)
  }
}
Example 33
Source File: readFileToBuffer.js    From ui with MIT License 8 votes vote down vote up
readFileToBuffer = (file) => {
  const reader = new FileReader();

  return new Promise((resolve, reject) => {
    reader.onabort = () => reject(new Error('aborted'));
    reader.onerror = () => reject(new Error('error'));
    reader.onload = () => resolve(Buffer.from(reader.result));

    reader.readAsArrayBuffer(file);
  });
}
Example 34
Source File: file-util.js    From bitmappery with MIT License 8 votes vote down vote up
readFile = ( file, optEncoding = "UTF-8" ) => {
    const reader = new FileReader();
    return new Promise(( resolve, reject ) => {
        reader.onload = readerEvent => {
            resolve( readerEvent.target.result );
        };
        reader.onerror = reject;
        reader.readAsText( file, optEncoding );
    });
}
Example 35
Source File: utils.node.js    From action-install-gh-release with Apache License 2.0 8 votes vote down vote up
/**
 * ONLY AVAILABLE IN NODE.JS RUNTIME.
 *
 * Writes the content of a readstream to a local file. Returns a Promise which is completed after the file handle is closed.
 *
 * @param rs - The read stream.
 * @param file - Destination file path.
 */
export async function readStreamToLocalFile(rs, file) {
    return new Promise((resolve, reject) => {
        const ws = fs.createWriteStream(file);
        rs.on("error", (err) => {
            reject(err);
        });
        ws.on("error", (err) => {
            reject(err);
        });
        ws.on("close", resolve);
        rs.pipe(ws);
    });
}
Example 36
Source File: magic.js    From jstest with GNU General Public License v3.0 8 votes vote down vote up
readFileSync(path) {
        try {
            return fs.readFileSync(path).toString();
        } catch (e) {
            console.log(path, '文件不存在进行创建')
            this.writeFileSync(path, '');
            return '';
        }
    }
Example 37
Source File: tools.js    From lx-music-mobile with Apache License 2.0 8 votes vote down vote up
handleReadFile = async(path) => {
  let isJSON = path.endsWith('.json')
  let data
  if (isJSON) {
    data = await readFile(path, 'utf8')
  } else {
    const tempFilePath = `${temporaryDirectoryPath}/tempFile.json`
    await ungzip(path, tempFilePath)
    data = await readFile(tempFilePath, 'utf8')
    await unlink(tempFilePath)
  }
  return JSON.parse(data)
}
Example 38
Source File: util.js    From editly with MIT License 8 votes vote down vote up
async function readVideoFileInfo(ffprobePath, p) {
  const streams = await readFileStreams(ffprobePath, p);
  const stream = streams.find((s) => s.codec_type === 'video'); // TODO

  const duration = await readDuration(ffprobePath, p);

  const rotation = stream.tags && stream.tags.rotate && parseInt(stream.tags.rotate, 10);
  return {
    // numFrames: parseInt(stream.nb_frames, 10),
    duration,
    width: stream.width, // TODO coded_width?
    height: stream.height,
    framerateStr: stream.r_frame_rate,
    rotation: !Number.isNaN(rotation) ? rotation : undefined,
  };
}
Example 39
Source File: utils.js    From vuforia-spatial-core-addon with Mozilla Public License 2.0 8 votes vote down vote up
/*
* This will parse the config file and apply the parameters to the interface
*/
function readConfigFile(file) {

    fetch(file)
        .then(response => {
            if (!response.ok) {
                throw new Error("HTTP error " + response.status);
            }
            return response.json();
        })
        .then(json => {
            this.config = json;
        })
        .catch(function () {
            this.dataError = true;
        })
}
Example 40
Source File: file_helpers.js    From saltcorn with MIT License 8 votes vote down vote up
export async function readJSON(fileName, dirName) {
  const dirEntry = await getDirEntry(dirName);
  return new Promise((resolve, reject) => {
    dirEntry.getFile(
      fileName,
      { create: false, exclusive: false },
      function (fileEntry) {
        fileEntry.file(function (file) {
          let reader = new FileReader();
          reader.onloadend = function (e) {
            resolve(JSON.parse(this.result));
          };
          reader.readAsText(file);
        });
      },
      function (err) {
        console.log(`unable to read  ${fileName}`);
        console.log(err);
        reject(err);
      }
    );
  });
}
Example 41
Source File: FabricUtils.js    From study-chain with MIT License 8 votes vote down vote up
/**
 *
 *
 * @param {*} config_path
 * @returns
 */
function readFileSync(config_path) {
	try {
		const config_loc = path.resolve(config_path);
		const data = fs.readFileSync(config_loc);
		return Buffer.from(data).toString();
	} catch (err) {
		logger.error(`NetworkConfig101 - problem reading the PEM file :: ${err}`);
		throw err;
	}
}
Example 42
Source File: promisify.js    From the-eye-knows-the-garbage with MIT License 8 votes vote down vote up
readFile = (inputFileSystem, path) => new Promise((resolve, reject) => {
  inputFileSystem.readFile(path, (err, stats) => {
    if (err) {
      reject(err);
    }

    resolve(stats);
  });
})
Example 43
Source File: CompilerHost.js    From the-eye-knows-the-garbage with MIT License 8 votes vote down vote up
readFile(path, encoding) {
        const content = this.tsHost.readFile(path, encoding);
        // get typescript contents from Vue file
        if (content && VueProgram_1.VueProgram.isVue(path)) {
            const resolved = VueProgram_1.VueProgram.resolveScriptBlock(this.typescript, content);
            return resolved.content;
        }
        return content;
    }
Example 44
Source File: promisify.js    From akaunting with GNU General Public License v3.0 8 votes vote down vote up
readFile = exports.readFile = function readFile(inputFileSystem, path) {
    return new Promise(function (resolve, reject) {
        inputFileSystem.readFile(path, function (err, stats) {
            if (err) {
                reject(err);
            }
            resolve(stats);
        });
    });
}
Example 45
Source File: utils.js    From webnn-polyfill with Apache License 2.0 8 votes vote down vote up
async function readFromNpy(fileName) {
  const dataTypeMap = new Map([
    ['f2', {type: 'float16', array: Uint16Array}],
    ['f4', {type: 'float32', array: Float32Array}],
    ['f8', {type: 'float64', array: Float64Array}],
    ['i1', {type: 'int8', array: Int8Array}],
    ['i2', {type: 'int16', array: Int16Array}],
    ['i4', {type: 'int32', array: Int32Array}],
    ['i8', {type: 'int64', array: BigInt64Array}],
    ['u1', {type: 'uint8', array: Uint8Array}],
    ['u2', {type: 'uint16', array: Uint16Array}],
    ['u4', {type: 'uint32', array: Uint32Array}],
    ['u8', {type: 'uint64', array: BigUint64Array}],
  ]);
  let buffer;
  if (typeof fs !== 'undefined') {
    buffer = fs.readFileSync(fileName);
  } else {
    const response = await fetch(fileName);
    buffer = await response.arrayBuffer();
  }
  const npArray = new numpy.Array(new Uint8Array(buffer));
  if (!dataTypeMap.has(npArray.dataType)) {
    throw new Error(`Data type ${npArray.dataType} is not supported.`);
  }
  const dimensions = npArray.shape;
  const type = dataTypeMap.get(npArray.dataType).type;
  const TypedArrayConstructor = dataTypeMap.get(npArray.dataType).array;
  const typedArray = new TypedArrayConstructor(sizeOfShape(dimensions));
  const dataView = new DataView(npArray.data.buffer);
  const littleEndian = npArray.byteOrder === '<';
  for (let i = 0; i < sizeOfShape(dimensions); ++i) {
    typedArray[i] = dataView[`get` + type[0].toUpperCase() + type.substr(1)](
        i * TypedArrayConstructor.BYTES_PER_ELEMENT, littleEndian);
  }
  return {buffer: typedArray, type, dimensions};
}
Example 46
Source File: file.js    From Wechatsync with GNU General Public License v3.0 8 votes vote down vote up
export function readFileToBase64(url) {
  return new Promise((resolve, reject) => {
    ;(async () => {
      let body = null
      try {
        const req = await axios.get(url, { responseType: 'blob' })
        body = req.data
      } catch (e) {
        return reject(e)
      }
      if (body != null) {
        const reader = new FileReader()
        reader.readAsDataURL(body)
        reader.onloadend = function () {
          var base64data = reader.result
          resolve(base64data)
        }
        reader.onerror = function (e) {
          reject(e)
        }
      }
    })()
  })
}
Example 47
Source File: util.js    From vue-cesium-v2 with MIT License 8 votes vote down vote up
export function readAsArrayBuffer (file) {
  const promise = defer()
  const fr = new FileReader()
  fr.onload = function (e) {
    promise.resolve(e.target.result)
  }
  fr.onprogress = function (e) {
    promise.progress(e.target.result)
  }
  fr.onerror = function (e) {
    promise.reject(e.error)
  }
  fr.readAsArrayBuffer(file)
  return promise
}
Example 48
Source File: util.js    From vue-cesium-v2 with MIT License 8 votes vote down vote up
export function readAsText (file) {
  const promise = defer()
  const fr = new FileReader()
  fr.onload = function (e) {
    promise.resolve(e.target.result)
  }
  fr.onprogress = function (e) {
    promise.progress(e.target.result)
  }
  fr.onerror = function (e) {
    promise.reject(e.error)
  }
  fr.readAsText(file)
  return promise
}
Example 49
Source File: util.js    From vue-cesium-v2 with MIT License 8 votes vote down vote up
export function readAllBytes (file) {
  const promise = defer()
  const fr = new FileReader()
  fr.onload = function (e) {
    promise.resolve(new Uint8Array(e.target.result))
  }
  fr.onprogress = function (e) {
    promise.progress(e.target.result)
  }
  fr.onerror = function (e) {
    promise.reject(e.error)
  }
  fr.readAsArrayBuffer(file)
  return promise
}
Example 50
Source File: GoogleLocalResultScrapper.js    From google_local_result_scrapper with MIT License 7 votes vote down vote up
/**
     * @description Reads the data from a JSON file
     * @param {String} fileName the name of the file to read
     * @return {Promise<Array/Object>} The parsed JSON
     */
    async readJsonData(fileName) {
        return new Promise((resolve, reject) => {

            fs.readFile(fileName, 'utf8', (error, data) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(JSON.parse(data));
                }
            })

        })
    }
Example 51
Source File: app.js    From noia with MIT License 7 votes vote down vote up
async function find(ls_func, readFile_func, path, query) {
	let fs = await ls_func(path, true, query);
	let fs_files_new = [];
	for (let file of fs.files) {
		file["file_type"] = null;
		if (file.isFile && file.size > 0 && file.path && getFilename(file.path).includes(query)) {
			file["file_type"] = "data";
			if(readFile_func !== null) {
				let fileContent = await readFile_func(file.path, 0x100); // partly read for detecting file type
				let file_type = await FileType.fromBuffer(new Uint8Array(fileContent));
				if (file_type !== undefined) {
					file["file_type"] = file_type.mime.startsWith("image") ? file_type.mime : file_type.ext;
				}
			}
			else {
				file["file_type"] = null;
			}
			fs_files_new.push(file);
		}
		if(file.isDirectory) {
			let recursiveLsResult = await find(ls_func, readFile_func, `${file.path}`, getFilename(file.path).includes(query) ? "" : query);
			fs_files_new = fs_files_new.concat(recursiveLsResult);
		}
	}
	return fs_files_new;
}
Example 52
Source File: KnexMigrator.js    From xgenecloud with Apache License 2.0 7 votes vote down vote up
async _readProjectJson(projJsonFilePath = null) {
    try {
      // projJsonFilePath = `${path.join(process.cwd(), "config.xc.json")}`;
      
      log.debug("_readProjectJson", projJsonFilePath);
      const exists = await promisify(fs.exists)(projJsonFilePath);

      if (exists) {
        // this.project = await promisify(jsonfile.readFile)(projJsonFilePath);
        this.project = await promisify(fs.readFile)(
          projJsonFilePath,
          "utf8"
        );
        this.project = JSON.parse(this.project, (key,value) => {
          return typeof value === 'string' ? Handlebars.compile(value,{noEscape:true})(process.env) : value ;
        });
        this.project.folder = this.project.folder || path.dirname(projJsonFilePath)
      } else {
        throw new Error("Project file should have got created");
      }
    } catch (e) {
      log.debug("error in _readProjectJson: ", e);
    }
  }
Example 53
Source File: cobertura.js    From cobertura-action with MIT License 7 votes vote down vote up
/**
 * generate the report for the given file
 *
 * @param path: string
 * @param options: object
 * @return {Promise<{total: number, line: number, files: T[], branch: number}>}
 */
async function readCoverageFromFile(path, options) {
  const xml = await fs.readFile(path, "utf-8");
  const { coverage } = await parseString(xml, {
    explicitArray: false,
    mergeAttrs: true,
  });
  const { packages } = coverage;
  const classes = processPackages(packages);
  const files = classes
    .filter(Boolean)
    .map((klass) => {
      return {
        ...calculateRates(klass),
        filename: klass["filename"],
        name: klass["name"],
        missing: missingLines(klass),
      };
    })
    .filter((file) => options.skipCovered === false || file.total < 100);
  return {
    ...calculateRates(coverage),
    files,
  };
}
Example 54
Source File: getHttpsConfig.js    From koronawirus.lol with GNU Affero General Public License v3.0 7 votes vote down vote up
// Read file and throw an error if it doesn't exist
function readEnvFile(file, type) {
  if (!fs.existsSync(file)) {
    throw new Error(
      `You specified ${chalk.cyan(
        type
      )} in your env, but the file "${chalk.yellow(file)}" can't be found.`
    );
  }
  return fs.readFileSync(file);
}
Example 55
Source File: hub.js    From Path-Finding-Visualizer with MIT License 7 votes vote down vote up
static readLocatorFile(projectId) {
        const locatorPath = this.getLocatorFilePath(projectId);
        if (!fs.existsSync(locatorPath)) {
            return undefined;
        }
        const data = fs.readFileSync(locatorPath, "utf8").toString();
        const locator = JSON.parse(data);
        if (locator.version !== this.CLI_VERSION) {
            logger.debug(`Found locator with mismatched version, ignoring: ${JSON.stringify(locator)}`);
            return undefined;
        }
        return locator;
    }
Example 56
Source File: optionsHelper.js    From Path-Finding-Visualizer with MIT License 7 votes vote down vote up
function readTestConfigFile(testConfigPath) {
    try {
        const buf = fs.readFileSync(path.resolve(testConfigPath));
        return JSON.parse(buf.toString());
    }
    catch (err) {
        throw new error_1.FirebaseError(`Error reading --test-config file: ${err.message}\n`, {
            original: err,
        });
    }
}
Example 57
Source File: paramHelper.js    From Path-Finding-Visualizer with MIT License 7 votes vote down vote up
function readParamsFile(envFilePath) {
    try {
        const buf = fs.readFileSync(path.resolve(envFilePath), "utf8");
        return dotenv.parse(buf.toString().trim(), { debug: true });
    }
    catch (err) {
        throw new error_1.FirebaseError(`Error reading --test-params file: ${err.message}\n`, {
            original: err,
        });
    }
}
Example 58
Source File: specHelper.js    From Path-Finding-Visualizer with MIT License 7 votes vote down vote up
function readFileFromDirectory(directory, file) {
    return new Promise((resolve, reject) => {
        fs.readFile(path.resolve(directory, file), "utf8", (err, data) => {
            if (err) {
                if (err.code === "ENOENT") {
                    return reject(new error_1.FirebaseError(`Could not find "${file}" in "${directory}"`, { original: err }));
                }
                reject(new error_1.FirebaseError(`Failed to read file "${file}" in "${directory}"`, { original: err }));
            }
            else {
                resolve(data);
            }
        });
    }).then((source) => {
        return {
            source,
            sourceDirectory: directory,
        };
    });
}
Example 59
Source File: localHelper.js    From Path-Finding-Visualizer with MIT License 7 votes vote down vote up
function readFile(pathToFile) {
    try {
        return fs.readFileSync(pathToFile, "utf8");
    }
    catch (err) {
        if (err.code === "ENOENT") {
            throw new error_1.FirebaseError(`Could not find "${pathToFile}""`, { original: err });
        }
        throw new error_1.FirebaseError(`Failed to read file at "${pathToFile}"`, { original: err });
    }
}
Example 60
Source File: fs.js    From Path-Finding-Visualizer with MIT License 7 votes vote down vote up
readFile = (0, _gensync().default)({
  sync: _fs().default.readFileSync,
  errback: _fs().default.readFile
})