我一直在努力成功下载图像而不用它将它传递给fs.这就是我所取得的成就:
var Promise = require('bluebird'),
fs = Promise.promisifyAll(require('fs')),
requestAsync = Promise.promisify(require('request'));
function downloadImage(uri, filename){
return requestAsync(uri)
.spread(function (response, body) {
if (response.statusCode != 200) return Promise.resolve();
return fs.writeFileAsync(filename, body);
})
.then(function () { ... })
// ...
}
Run Code Online (Sandbox Code Playgroud)
有效输入可能是:
downloadImage('http://goo.gl/5FiLfb', 'c:\\thanks.jpg');
Run Code Online (Sandbox Code Playgroud)
我确实认为问题在于处理问题body.我已经尝试将其转换为Buffer(new Buffer(body, 'binary')等)几种编码,但都失败了.
感谢前方的任何帮助!
我有两个节点线程在运行,一个观察目录以使用文件,另一个负责将文件写入给定目录。
通常,它们不会在同一目录上运行,但对于我正在处理的边缘情况,它们将是。
似乎消费应用程序在文件被完全写入之前抓取文件,导致文件损坏。
有没有办法锁定文件直到写入完成?我已经研究过这个lockfile模块,但不幸的是我不相信它适用于这个特定的应用程序。
======
把完整的代码放在这里远远没有意义,但它的要点是:
听众:
fs.writeFile观察者:
chokidar跟踪每个被监视目录中添加的文件fs.access被调用以确保我们可以访问该文件
fs.access 似乎对正在写入的文件无动于衷fs.createReadStream然后发送到服务器
在这种情况下,文件被导出到被监视的目录,然后被监视进程重新导入。
我有这个json:
var myJSON = '{"kind": "person", "fullName": "Rivka3"}';
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用createReadStream将它上传到bigquery.当我保存它localy我成功:
fs.writeFile("/tmp/bq_json_file_new.json", myJSON, function(err){});
fs.createReadStream("/tmp/bq_json_file_new.json")
.pipe(table.createWriteStream(metadata))
.on('complete', function(job) {
job
.on('error', console.log)
.on('complete', function(metadata) {
console.log('job completed', metadata);
});
});
Run Code Online (Sandbox Code Playgroud)
现在我试图这样做而不保存它localy - 使用缓冲区:
fs.createReadStream(new Buffer(myJSON, "utf8"))
.pipe(table.createWriteStream(metadata))
.on('complete', function(job) {
job
.on('error', console.log)
.on('complete', function(metadata) {
console.log('job completed', metadata);
});
});
Run Code Online (Sandbox Code Playgroud)
但我收到这个错误:
fs.js:575
binding.open(pathModule._makeLong(path),
TypeError: path must be a string
Run Code Online (Sandbox Code Playgroud) 码:
fs.unlink("/public/images/uploads/"+req.file.filename, (err) => {
if (err) {
console.log("failed to delete local image:"+err);
} else {
console.log('successfully deleted local image');
}
});
Run Code Online (Sandbox Code Playgroud)
控制台/终端的错误消息:
failed to delete local image:Error: ENOENT: no such file or directory, unlink '/public/images/uploads/ed6d810405e42d0dfd03d7668e356db3'
Run Code Online (Sandbox Code Playgroud)
情况
我必须指定错误的路径.我不明白为什么会出错," public"文件夹与" "文件处于同一级别app.js." upload.js"位于名为" routes" 的文件夹中,与" app.js" 处于同一级别.
我已经在我的app.js中为我的公共文件夹指定了一个"/ public"路由:
//Static Folder
app.use("/public",express.static(path.join(__dirname, "/public")));
Run Code Online (Sandbox Code Playgroud)
题:
我做错了什么?
我正在使用Angular 7。
我试图在Typescript上使用fs模块打开目录。我总是遇到以下错误:“未找到模块:错误:无法解析fs”类型@节点和文件系统已安装。
我的代码:
import {Component, OnInit} from '@angular/core';
import * as fs from 'file-system';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'my-app';
constructor() {
}
ngOnInit() {
console.log(fs);
}
}
Run Code Online (Sandbox Code Playgroud)
你能帮助我吗 ?
节点:v10.14.0 Npm:v6.4.1 Angular CLI:v7.1.1
出于好奇,我想知道两者之间是否有任何区别。
读取文件同步:
function parseFile(filePath) {
let data = fs.readFileSync(filePath);
}Run Code Online (Sandbox Code Playgroud)
使用promisify读取文件:
const readFilePromise = promisify(fs.readFile);
async function parseFile(filePath) {
let data = await readFilePromise(filePath);
}Run Code Online (Sandbox Code Playgroud)
如果您需要一些上下文,我会尝试读取文件夹中的一堆文件,替换每个文件中的大量值,然后再次写入。
我不知道对这些操作使用 Asyncronous 或 Synchronous 代码是否有任何区别。
完整代码:
function parseFile(filePath) {
let data = fs.readFileSync(filePath);
let originalData = data.toString();
let newData = replaceAll(originalData);
return fs.writeFileSync(filePath, newData);
}
function readFiles(dirPath) {
let dir = path.join(__dirname, dirPath);
let files = fs.readdirSync(dir); // gives all the files
files.map(file => parseFile(path.join(dir, file)));
}
function replaceAll(text) {
text = text.replace(/a/g, 'b'); …Run Code Online (Sandbox Code Playgroud)我需要删除目录中除我指定名称的文件之外的所有文件。比方说:
fs.unlink('./all except specialfile.txt', (err)) => {
if (err) throw err;
console.log('file deleted!');
}
Run Code Online (Sandbox Code Playgroud) 这是我的场景:
我尝试了很多方法,但无法向用户打开该文件。
我尝试过的方法:
const buff = Buffer.from(myBase64, 'base64');
const file = fs.writeFileSync('boleto.pdf', buff, { encoding: 'base64' });
try {
res.setHeader('Content-Length', file.size);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=boleto.pdf');
} catch (e) {
return res.status(404).send({ error: e, message: 'File does not exist.', statusCode: 404 });
}
Run Code Online (Sandbox Code Playgroud)
const buff = Buffer.from(myBase64, 'base64');
const file = fs.writeFileSync('boleto.pdf', buff, { encoding: 'base64' });
try {
res.contentType('application/pdf');
return res.status(200).sendFile('boleto');
} catch …Run Code Online (Sandbox Code Playgroud) 我试图爬行几个网页来检查损坏的链接并将链接的结果写入 json 文件,但是,在第一个文件完成后,应用程序崩溃,没有弹出错误...
我使用 Puppeteer 进行爬行,使用 Bluebird 来同时运行每个链接,使用 fs 来写入文件。
我尝试过什么:
const express = require('express');
const router = express.Router();
const puppeteer = require('puppeteer');
const bluebird = require("bluebird");
const fs = require('fs');
router.get('/', function(req, res, next) {
(async () => {
// Our (multiple) URLs.
const urls = ['https://www.testing.com/allergy-test/', 'https://www.testing.com/genetic-testing/'];
const withBrowser = async (fn) => {
const browser = await puppeteer.launch();
try {
return await fn(browser);
} finally {
await browser.close();
} …Run Code Online (Sandbox Code Playgroud) 我尝试使用 fetch() 函数从 github 下载文件。
然后我尝试将获取的文件流保存为带有 fs 模块的文件。
执行此操作时,我收到此错误:
TypeError [ERR_INVALID_ARG_TYPE]:“transform.writable”属性必须是 WritableStream 的实例。收到 WriteStream 的实例
我的问题是,我不知道 WriteStream 和 WritableStream 之间的区别或如何转换它们。
这是我运行的代码:
async function downloadFile(link, filename = "download") {
var response = await fetch(link);
var body = await response.body;
var filepath = "./" + filename;
var download_write_stream = fs.createWriteStream(filepath);
console.log(download_write_stream.writable);
await body.pipeTo(download_write_stream);
}
Run Code Online (Sandbox Code Playgroud)
Node.js:v18.7.0
fs ×10
node.js ×9
bluebird ×2
javascript ×2
promise ×2
angular ×1
angular7 ×1
async-await ×1
download ×1
file ×1
node-request ×1
pdf ×1
puppeteer ×1
stream ×1
typescript ×1